不久前我做了一件非常相似的事情,我通过作弊做到了。
如果您发现内置的重写规则过于复杂或无法执行作业,您可能会发现更容易捕获请求并过滤结果。一个简化的版本:
add_action('parse_request', 'my_parse_request');
function my_parse_request (&$wp) {
$path = $wp->request;
$groups = array();
if (preg_match("%shop/product/([a-zA-Z0-9-]+)%", $path, $groups)) {
$code = $groups[1];
$product = get_product($code); // your own code here
if (isset($product)) {
add_filter('the_posts', 'my_product_filter_posts');
}
}
}
function my_product_filter_posts ($posts) {
ob_start();
echo "stuff goes here"; // your body here
$content = ob_get_contents();
ob_end_clean();
return array(new DummyResult(0, "Product name", $content));
}
为了解释:
上parse_request
该操作将在数据库中查找之前调用。根据URL,它会安装其他操作和过滤器。
帖子上的过滤器用假结果替换数据库查找的结果。
DummyResult是一个简单的类具有相同的字段后,或刚好够他们用它来逃脱:
class DummyResult {
public $ID;
public $post_title;
public $post_content;
public $post_author;
public $comment_status = "closed";
public $post_status = "publish";
public $ping_status = "closed";
public $post_type = "page";
public $post_date = "";
function __construct ($ID, $title, $content) {
$this->ID = $ID;
$this->post_title = $title;
$this->post_content = $content;
$this->post_author = get_default_author(); // implement this function
}
}
有留在读者很多功课以上,但这是一种丑陋的工作方式。您可能需要为template_redirect
添加一个过滤器,以将产品特定的页面模板替换为常规页面模板。如果你想要漂亮的固定链接,你可能需要调整URL正则表达式。