简体   繁体   中英

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

I have a custom post type "event" and a custom taxonomy "event-category". In that taxonomy I have a term "news". What i'd like is to add only the events with the term "news" to my main loop.

I have this code that will merge my events and posts but I don't know how to limit that to a specific term... Any ideas?

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' );

Update your function to add the tax_query query var :

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' );

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM