将分类法中特定术语的自定义帖子类型添加到主循环(Wordpress)


Adding a custom post type from a specific term in a taxonomy to the main loop (Wordpress)

我有一个自定义帖子类型"event"和一个自定义分类法"event-category"。在这个分类中,我有一个术语"新闻"。我想要的是只添加带有术语"news"的事件到我的主循环。

我有这个代码,将合并我的事件和帖子,但我不知道如何限制到一个特定的术语…什么好主意吗?

function add_custom_post_type_to_query( $query ) {
if ( $query->is_home() && $query->is_main_query() ) {
    $query->set( 'post_type', array('post', 'event') );
  }
}
add_action( 'pre_get_posts', 'add_custom_post_type_to_query' );

更新您的函数以添加tax_query查询变量:

function add_custom_post_type_to_query( $query ) {
if ( $query->is_home() && $query->is_main_query() ) {
    $query->set( 'post_type', array('post', 'event') );
    $query->set( 'tax_query', array(array(
        'taxonomy' => 'event-category',
        'terms' => 'news'
    )));
  }
}
add_action( 'pre_get_posts', 'add_custom_post_type_to_query' );