这是为了创建一个定制的RSS提要。我有一个名为引号的CPT和一个名为quote_category的分类法
我希望所有的帖子都是quote_category = 'Dogs‘,ID = 115。这不管用:
$postCount = 10; // The number of posts to show in the feed
$postType = 'quotes'; // post type to display in the feed
$catName = 'Dogs';
$posts = query_posts(array('post_type'=>$postType, 'quote_category'=>$catName, 'showposts' => $postCount));
发布于 2021-04-28 07:32:36
一般来说,共识是避免 query_posts
不惜一切代价的。正式文件甚至支持这一点:
注意:此函数将完全覆盖主查询,不适合插件或主题使用。它过于简单的修改主查询的方法可能会有问题,应该尽可能避免。在大多数情况下,修改主查询有更好、更高性能的选项,例如通过WP_Query中的‘WP_Query’操作。
相反,get_posts()
会做您希望它做的任何事情。对于您的情况,您只需要在tax_query
上添加您的信息。
$posts = get_posts(
[
'post_type' => 'quotes',
'numberposts' => 10,
'tax_query' => [
[
'taxonomy' => 'quote_category',
'field' => 'name',
'terms' => 'Dogs',
],
],
]
)
如果需要多个数组,terms
参数还接受一个数组:
'terms' => ['Dogs', 'Cats'],
编辑
如果您使用的是get_template_part
,那么您可能也在使用标准的WordPress循环。这实际上是您可以使用query_posts
的少数几次之一,但我个人仍然不使用它,也不推荐它。在理想情况下,您可能会像使用pre_get_posts
一样使用过滤器,但不幸的是,我没有时间编写代码来测试它。您应该能够使用以下代码。
此代码是一个调用匿名函数的操作,该函数使用另一个匿名函数作为回调添加提要。您的代码做了完全相同的事情,但是您使用的是100%精细、安全和常见的命名函数。我个人更喜欢把我的钩子和逻辑放在一起,而不是追逐名字。再一次,完全的个人偏好。
如果仍然收到内部错误,请确保启用了WordPress和PHP调试,以便您可以看到实际错误是什么,这可能是我的错误。
add_action(
'init',
static function () {
add_feed(
'quotes',
static function () {
// Override the main query since the render functions wants to use the loop
global $wp_query;
$wp_query = new WP_Query(
[
'post_type' => 'quotes',
'post_count' => 10,
'tax_query' => [
[
'taxonomy' => 'quote_category',
'field' => 'name',
'terms' => 'Dogs',
],
],
]
);
get_template_part('rss', 'quotes');
}
);
}
);
https://stackoverflow.com/questions/67303040
复制