不久前我做了一件非常相似的事情,我是通过作弊来做到的。
如果您发现内置的重写规则过于复杂或无法完成这项工作,您可能会发现更容易捕获请求并过滤结果。简化版:
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 正则表达式。