我正在尝试创建一些漂亮的URL来显示分类页面中的内容。例如:https://example.com/resources/white-paper (不是真正的WP页面)将显示https://example.com/resources/?type=white-paper. /资源是自定义帖子类型的归档页面,归档页面模板提取查询字符串并显示相应分类法的帖子。关于如何处理这个问题,有什么建议吗?
URL rewrites af
2 个回复
SO网友:Nour Edin Al-Habal
function wpse325663_rewrite_resource_type() {
add_rewrite_rule(\'^resources\\/(.+)/?\', \'resources/?type=$matches[1]\', \'top\');
}
add_action(\'init\', \'wpse325663_rewrite_resource_type\');
来自the codex:修改规则后,不要忘记刷新和重新生成重写规则数据库。从…起WordPress Administration Screens, 选择设置->永久链接,只需单击保存更改而不做任何更改。
SO网友:WebElaine
只要您只处理一个CPT,当您注册帖子类型时,请确保设置has_archive
至true和rewrite
到array(\'slug\' => \'resources\')
. 这样,您就可以通过编程方式创建存档。
(如果您没有设置has_archive
首次注册CPT时,您可能需要unregister_post_type()
它不会删除您的帖子,但会将其清除,然后用新设置重新注册。最后,访问永久链接设置页面以刷新永久链接。)
然后,在子主题或自定义主题中,创建一个名为archive-resources.php
. 这是您可以截取查询字符串并适当响应的地方。基本结构如下:
<?php
// if the query string is present
if($_GET[\'type\']) {
get_header();
// run your tax query here
$args = array(
\'post_type\' => \'post\',
// tax query is an array of arrays
\'tax_query\' => array(
array(
\'taxonomy\' => \'type\',
// you can pull various ways; this uses the slug i.e. \'white-paper\'
\'field\' => \'slug\',
\'terms\' => $_GET[\'type\']
)
)
);
$posts = new WP_Query($args);
if($posts->have_posts()) {
while($posts->have_posts()): $posts->the_post();
// your loop here
endwhile;
}
get_footer();
} else {
// what to do if no query string is present
// example: you could redirect elsewhere, or show a default taxonomy query
}
缺点是存档将运行默认查询,因此基本上是将该查询的结果抛出窗口,然后运行自己的查询。您可以在else
条件并利用它,因为它无论如何都会运行。