我想在最近的帖子小部件中显示自定义帖子类型的帖子。我正在使用一个名为“高级最近发布的窗口小部件”的窗口小部件来执行此操作。它适用于除首页以外的所有页面。在主页上,它显示了最近的帖子窗口小部件中的所有自定义帖子类型的帖子。
我将使用此代码在首页上显示所有自定义帖子类型的帖子。
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;
});
我想在首页上显示所有自定义帖子类型的帖子,但是最近的帖子小部件中仅显示一种自定义帖子类型。它应该仅在最近的窗口小部件中显示测试,而不在其他帖子中显示。
我试图更改显示主页上所有帖子的代码,但没有成功。
您正在使用更改查询,pre_get_posts
以包括主页上的所有帖子类型,但实际上是在更改主页上的所有或所有查询。
在您的函数中,您正在检查is_home() or is_front_page()
以确保它仅在主页上运行。您只需要在此处添加一个条件即可检查它是否也是主查询,以免影响小部件中的查询。您可以使用进行此操作$query->is_main_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... */
}
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句