Wordpress 为什么所有自定义帖子类型都显示在最近的帖子小部件中?
我想在“最近的帖子”小部件中显示自定义帖子类型的帖子。我正在使用一个名为AdvancedRecentPostsWidget的小部件来完成它。它可以在除主页外的所有页面上运行。在主页上,它显示了“最近的帖子”小部件中的所有自定义帖子类型 我用这个代码在主页上显示所有自定义帖子类型的帖子Wordpress 为什么所有自定义帖子类型都显示在最近的帖子小部件中?,wordpress,Wordpress,我想在“最近的帖子”小部件中显示自定义帖子类型的帖子。我正在使用一个名为AdvancedRecentPostsWidget的小部件来完成它。它可以在除主页外的所有页面上运行。在主页上,它显示了“最近的帖子”小部件中的所有自定义帖子类型 我用这个代码在主页上显示所有自定义帖子类型的帖子 add_action('pre_get_posts', function(WP_Query $query){ if(is_admin() or is_preview()){ return;
add_action('pre_get_posts', function(WP_Query $query){
if(is_admin() or is_preview()){
return;
}
// Only add them to the loop on Home/Front-Page
if((is_home() or is_front_page()) and empty($query->query_vars['suppress_filters'])){
// This has to be an array so fix it if required
$post_types = $query->get('post_type');
if(empty($post_types)) $post_types = array('post');
elseif(is_string($post_types)) $post_types = array($post_types);
// Add one or more CPT-s to the loop here (merge old with new)
$query->set('post_type', array_merge($post_types, array(
'videos',
'academic-articles',
'news-events'
// 'another_post_type',
// 'maybe_another_post_type',
)));
}
return;
});
我想在主页上显示所有自定义帖子类型,但在最近的帖子小部件中只显示一个自定义帖子类型。它应该只在最近的小部件中显示Test,而不是其他帖子
我试图更改显示主页上所有帖子的代码,但没有成功。您正在使用
pre\u get\u posts
更改查询,以包括主页上的所有帖子类型,但实际情况是,它正在更改主页上的此查询或所有查询
在函数中,您要检查是主页()还是首页()
,以确保它只在主页上运行。您只需在此处添加一个条件,以检查它是否也是主查询,这样它就不会影响小部件中的查询。您可以使用$query->is\u main\u query()
执行此操作
因此,您的if
现在将如下所示:
if( (is_home() or is_front_page())
and $query->is_main_query() /* <- ADD THIS so it only runs on the main query */
and empty($query->query_vars['suppress_filters'])){
/* it's the main query on the homepage so it's ok change the post types... */
}
if((是首页()还是首页())
和$query->is_main_query()/*query_vars['suppress_filters'])){
/*这是主页上的主要查询,所以可以更改帖子类型*/
}