使用add_rewrite_endpoint
<?php
if ( ! class_exists( \'PDFRewriteEndpoint\' ) ):
class PDFRewriteEndpoint {
/**
* Add actions and filters in constructor.
*/
public function __construct() {
add_action( \'parse_request\', array ( $this, \'sniff_requests\' ), 0 );
add_action( \'init\', array ( $this, \'add_endpoint\' ), 0 );
}
/**
* Add rewrite rules.
*/
public function add_endpoint() {
// article-slug/pdf/
add_rewrite_endpoint( \'pdf\', EP_PERMALINK | EP_PAGES );
//////////////////////////////////
flush_rewrite_rules( true ); //// <---------- REMOVE THIS WHEN DONE TESTING
//////////////////////////////////
}
/**
* Redirect to PDF page or download
*
* @param $wp_query
*/
public function sniff_requests( $wp_query ) {
if ( isset( $wp_query->query_vars[ \'pdf\' ] ) ) {
// anything after `/pdf/` like `extra/stuff`
$pdf_extras = $wp_query->query_vars[ \'pdf\' ];
echo $pdf_extras . PHP_EOL;
// Do PDF Logic Here
wp_die(\'PDF of \' . $wp_query->query_vars[\'name\']);
}
}
}
// Create the class
$pdfRewriteEndpoint = new PDFRewriteEndpoint();
endif; // PDFRewriteEndpoint
使用
add_rewrite_rule
<?php
if ( ! class_exists( \'PDFRewrite\' ) ):
class PDFRewrite {
const ENDPOINT_QUERY_PARAM = \'____pdf_api\';
/**
* Add actions and filters in constructor.
*/
public function __construct() {
add_filter( \'query_vars\', array ( $this, \'add_query_vars\' ), 0 );
add_action( \'parse_request\', array ( $this, \'sniff_requests\' ), 99 );
add_action( \'init\', array ( $this, \'add_endpoint\' ), 0 );
}
/**
* Add our custom query arg to later check in `parse_request`.
*
* @param $vars
*
* @return array
*/
public function add_query_vars( $vars ) {
$vars[] = static::ENDPOINT_QUERY_PARAM;
return $vars;
}
/**
* Add rewrite rules.
*/
public function add_endpoint() {
// article-slug/pdf/
add_rewrite_rule( "^([^/]+)/pdf/?$", \'index.php?\' . static::ENDPOINT_QUERY_PARAM . \'=1&name=$matches[1]\', \'top\' );
//////////////////////////////////
flush_rewrite_rules( true ); //// <---------- REMOVE THIS WHEN DONE TESTING
//////////////////////////////////
}
/**
* Redirect to PDF page or download
*
* @param $wp_query
*/
public function sniff_requests( $wp_query ) {
global $wp;
if ( isset( $wp->query_vars[ static::ENDPOINT_QUERY_PARAM ] ) ) {
// Do PDF Logic Here
wp_die(\'PDF of \' . $wp->query_vars[\'name\']);
exit;
}
}
}
// Create the class
$pdfRewrite = new PDFRewrite();
endif; // PDFRewrite