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 beterm_id
, notid
.id
works, so will any crap passed as value because if you look at the source codes, the source only checks forslug
andname
, it does not specifically check forterm_id
. So any value will work as default. This is wrong. The correct and only value for term ids isterm_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 termuncategorized
. This is why your query fails to get posts.uncategorized
is a term to the build in taxonomycategory
, not the custom taxonomycpt-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 defaultpost_type
on the homepage ispost
, always if not modified by some kind of filter likepre_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' );
}