Site icon Hip-Hop Website Design and Development

Including a tax_query to a WP_Query Object

Is it doable to switch a WP_Query object so as to add a tax_query?

That’s — I will add a tax_query when instantiating a WP_Query object

$q = new WP_Query(array(
    'post_type' => 'put up',
    'tax_query' => array(
        array(
            'taxonomy' => 'post_format',
            'subject' => 'slug',
            'phrases' => array(
                'post-format-link',
            ),
            'operator' => 'IN'
        )
    )
));

The above question solely returns posts with a hyperlink format.

Nevertheless, if I’ve an already instantiated WP_Query object, I am not in a position to set a tax_query. If I attempt it like this

$q = new WP_Query(['post_type'=>'post']);
$q->set('tax_query', array(
    array(
        'taxonomy' => 'post_format',
        'subject' => 'slug',
        'phrases' => array(
            'post-format-link',
        ),
        'operator' => 'IN'
    )
));

My question returns all put up sorts, not simply hyperlink posts.

Is that this doable to do? In that case, am I utilizing set flawed, or do tax queries must be set in another way?

If it helps, the bigger context is I am attempting to alter a question object within the pre_get_posts action-hook. I have been in a position to make use of the pre_get_posts hook so as to add a class filter to a question

    add_action('pre_get_posts', operate($question) {
        if(!$query->is_main_query() || is_admin() || !is_front_page()) {
            return;
        }
        $time period = get_category_by_slug('my-slug');
        if(!$time period || !is_numeric($term->term_id)) {
            return;
        }
        $query->set('category__not_in', $term->term_id);
    });

With the above in place my entrance web page omits posts with the my-slug class.

Nevertheless, if I attempt an analogous factor with a tax_query, the entrance web page will not be restricted to hyperlink posts. The next

    add_action('pre_get_posts', operate($question) {
        if(!$query->is_main_query() || is_admin() || !is_front_page()) {
            return;
        }
        // per a solution under, I've tried issues each with and with out
        // this subsequent line and haven't had luck in getting my tax_query 
        // to use to the WP_Query
        // $tax_query = $query->get( 'tax_query', [] );        
        
        $query->set('tax_query',
            array(
                'taxonomy' => 'post_format',
                'subject' => 'slug',
                'phrases' => array(
                    'post-format-link',
                ),
                'operator' => 'IN'
            )
        );
    });

has no impact on the worldwide question for the entrance web page.