taxonomy – is_main_query() unexpected results

Question

I need to add product filtering using WooCommerce Attributes via URL vars, but have a small issue.

While the below function will work, adding is_main_query() as a condition is preventing this to run, any ideas why this might be?

This seems to be related just to the is_main_query() aspect from testing, but from what I’ve read, this is required to prevent the function being applied on other elements (for example, the main navigation won’t load if left off).

add_action( 'pre_get_posts', '_query_by_attribute' );

function _query_by_attribute( $query ) {

  if ( is_product_category() && $query->is_main_query() && !is_admin() && false !== strpos($_SERVER['REQUEST_URI'], '?') ) {

    // Setup tax array
    $tax_query = array();

    // Get current taxonomy object and add to tax array
    $object = get_queried_object();

    $tax_query[] = array(
      'taxonomy' => $object->taxonomy,
      'field'    => 'slug',
      'terms'    => $object->slug
    );

    // Parse URL for varibles
    $parts = parse_url($_SERVER['REQUEST_URI']);
    parse_str($parts['query'], $vars);

    foreach($vars as $key => $value) {

      $tax_query[] = array(
        'taxonomy' => $key,
        'field'    => 'slug',
        'terms'    => $value
      );

    };

    // Output query
    $query->set(
      'tax_query', $tax_query
    );

  }

}

0
user1235285 1 month 2021-10-18T01:59:37-05:00 0 Answers 0 views 0

Leave an answer

Browse
Browse