pre_get_posts all posts and custom post type with certain tag

You have a couple of issues here

  • is_home() should be a method of $query, so it should become $query->is_home()

  • The value to the field parameter should be term_id, not id. id works, so will any crap passed as value because if you look at the source codes, the source only checks for slug and name, it does not specifically check for term_id. So any value will work as default. This is wrong. The correct and only value for term ids is term_id

  • pre_get_posts is an action, not a filter

  • Actions do not return, so remove return $query

  • 1 cannot be your term id. 1 is the (reserved) term id of the default category term uncategorized. This is why your query fails to get posts. uncategorized is a term to the build in taxonomy category, not the custom taxonomy cpt-tag

  • Your custom taxonomy cannot be cpt-tag. Taxonomy names should always be lowercase letters (caveat – seems numbers are allowed as well if not the first digit) with multiple words separated by an underscore only. Hyphens should be avoided as it creates issues with template names etc

  • Your conditional check if ( $query->query_vars['post_type'] == 'cpt' ) {} is also probably never returning true due to being the home page. The default post_type on the homepage is post, always if not modified by some kind of filter like pre_get_posts. I would just remove this.

EDIT

From your edit, and comment, you need to remove post from the post_type array if you don’t need the deafult post type posts to display. You also do not need the 1 == 1 check.

Your final code should be:

add_action( 'pre_get_posts', 'get_posts_plus_cpt_with_certain_tag' );

function get_posts_plus_cpt_with_certain_tag( $query ) {
   if ( $query->is_home() && $query->is_main_query() ) {

         $taxquery = array(
            array(            
               'taxonomy' => 'cpt_tag',
               'field' => 'term_id',
               'terms' => 27
               )
            );      
            $query->set('tax_query', $taxquery);        
         }  
      $query->set( 'post_type', 'cpt' );

}

Leave a Comment