wp query – tax_query in pre_get_posts


I’m trying to add a tax_query for the query of a custom post type single page with this code.

function wcua_pre_get_posts ($query) {
    // Also removed this condition
    if( is_admin() || ! $query->is_main_query() ) {

    $contest = get_query_var('contest');
    if( ! empty($contest) ) {
        $query->set('tax_query', [
                'taxonomy' => 'contest',
                'field'    => 'slug',
                'terms'    => [$contest], // Also sent it as a string and removed the operator
                'operator' => 'IN'
add_action('pre_get_posts', 'wcua_pre_get_posts');

But it does not work. The result is not filtered. To test that it reaches that condition, I added a breakpoint and it does but the result is not filtered. Besides that I also added another thing $query->set('post__not_in', [1]) just to test and it does appear in the query, and the result does not change but I know the query changes.

I searched on the whole site and there are a few hooks for pre_get_posts but nont alter the tax_query. Also change the priority to 10k.

This is the register_taxonomy code for the custom post type

register_taxonomy('contest', 'entry', [
    'hierarchical'          => true,
    'labels'                => [
        'name'                       => _x( 'Contests', 'taxonomy general name' ),
        'singular_name'              => _x( 'Contest', 'taxonomy singular name' )
    'show_ui'               => true,
    'show_admin_column'     => true,
    'query_var'             => true,
    'publicly_queryable'    => true,
    'rewrite'               => array( 'slug' => 'contest' )

// Doing a rewrite rule for the CPT 
add_rewrite_rule('^([a-z-]+)/([0-9]+)/([a-z]+)/?', 'index.php?post_type=entry&contest=$matches[1]&contest_year=$matches[2]&name=$matches[3]', 'top');
add_rewrite_tag('%contest_year%', '([0-9]+)va');

// Query vars are set

Printed the $wp_query to see what it has and I see the tax_query in the query_vars array with what I added, but the tax_query property is NULL.

add_action('the_post', function() {
    global $wp_query; 
    echo '<pre>';
    echo '</pre>';

What could I be doing wrong? Did I forget something? Queries for CPT individual pages can’t be changed?

Jose Adrian 1 month 2022-08-18T19:47:32-05:00 0 Answers 0 views 0

Leave an answer