Adding a tax_query to a WP_Query Object

Is it possible to modify a WP_Query object to add a tax_query?

That is — I’m able to add a tax_query when instantiating a WP_Query object

$q = new WP_Query(array(
    'post_type' => 'post',
    'tax_query' => array(
        array(
            'taxonomy' => 'post_format',
            'field' => 'slug',
            'terms' => array(
                'post-format-link',
            ),
            'operator' => 'IN'
        )
    )
));

The above query only returns posts with a link format.

However, if I have an already instantiated WP_Query object, I’m not able to set a tax_query. If I try it like this

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

My query returns all post types, not just link posts.

Is this possible to do? If so, am I using set wrong, or do tax queries need to be set differently?

If it helps, the larger context is I’m trying to change a query object in the pre_get_posts action-hook. I’ve been able to use the pre_get_posts hook to add a category filter to a query

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

With the above in place my front page omits posts with the my-slug category.

However, if I try a similar thing with a tax_query, the front page is not restricted to link posts. The following

    add_action('pre_get_posts', function($query) {
        if(!$query->is_main_query() || is_admin() || !is_front_page()) {
            return;
        }
        // per an answer below, I've tried things both with and without
        // this next line and have not had luck in getting my tax_query 
        // to apply to the WP_Query
        // $tax_query = $query->get( 'tax_query', [] );        
        
        $query->set('tax_query',
            array(
                'taxonomy' => 'post_format',
                'field' => 'slug',
                'terms' => array(
                    'post-format-link',
                ),
                'operator' => 'IN'
            )
        );
    });

has no effect on the global query for the front page.

$299 Affordable Web Design WordPress

This article was republished from its original source.
Call Us: 1(800)730-2416

Pixeldust is a 20-year-old web development agency specializing in Drupal and WordPress and working with clients all over the country. With our best in class capabilities, we work with small businesses and fortune 500 companies alike. Give us a call at 1(800)730-2416 and let’s talk about your project.

FREE Drupal SEO Audit

Test your site below to see which issues need to be fixed. We will fix them and optimize your Drupal site 100% for Google and Bing. (Allow 30-60 seconds to gather data.)

Powered by

Adding a tax_query to a WP_Query Object

On-Site Drupal SEO Master Setup

We make sure your site is 100% optimized (and stays that way) for the best SEO results.

With Pixeldust On-site (or On-page) SEO we make changes to your site’s structure and performance to make it easier for search engines to see and understand your site’s content. Search engines use algorithms to rank sites by degrees of relevance. Our on-site optimization ensures your site is configured to provide information in a way that meets Google and Bing standards for optimal indexing.

This service includes:

  • Pathauto install and configuration for SEO-friendly URLs.
  • Meta Tags install and configuration with dynamic tokens for meta titles and descriptions for all content types.
  • Install and fix all issues on the SEO checklist module.
  • Install and configure XML sitemap module and submit sitemaps.
  • Install and configure Google Analytics Module.
  • Install and configure Yoast.
  • Install and configure the Advanced Aggregation module to improve performance by minifying and merging CSS and JS.
  • Install and configure Schema.org Metatag.
  • Configure robots.txt.
  • Google Search Console setup snd configuration.
  • Find & Fix H1 tags.
  • Find and fix duplicate/missing meta descriptions.
  • Find and fix duplicate title tags.
  • Improve title, meta tags, and site descriptions.
  • Optimize images for better search engine optimization. Automate where possible.
  • Find and fix the missing alt and title tag for all images. Automate where possible.
  • The project takes 1 week to complete.