• 5 Subscribers
  • 114 Views
1

Trying to exclude a single category from my WooCommerce's Shop Page

I was using this code but it would break my sites's attributes filter links:

add_action( 'pre_get_posts', 'custom_pre_get_posts_query' );

function custom_pre_get_posts_query( $q ) {

    if ( ! $q->is_main_query() ) return;
    if ( ! $q->is_post_type_archive() ) return;

    if ( ! is_admin() && is_shop() ) {

        $q->set( 'tax_query', array(array(
           'taxonomy' => 'product_cat',
           'field' => 'slug',
           'terms' => array( 'samples' ), 
           'operator' => 'NOT IN'
        )));

     }

     remove_action( 'pre_get_posts', 'custom_pre_get_posts_query' );

}

1 answers in total

1
helgatheviking Posted at 2017-01-12 02:35:47Z

You could use the woocommerce_product_query hook, which is pretty similar to pre_get_posts except it already has the appropriate conditional logic. There is also a woocommerce_product_query_tax_query filter, but I'm not sure if that is exists in WooCommerce 2.6 or if its new in 2.7 beta.

add_action( 'woocommerce_product_query', 'custom_pre_get_posts_query' );

function custom_pre_get_posts_query( $q ) {

    $q->set( 'tax_query', array(array(
       'taxonomy' => 'product_cat',
       'field' => 'slug',
       'terms' => array( 'samples' ), 
       'operator' => 'NOT IN'
    )));

}

EDIT filtering is done through the taxonomy query, and in the above example we're overriding the tax query completely. I can't test that this works right now (and arrays of arrays are tricky so I may have messed up), but the theory is that we need to merge the new constraint with the existing taxonomy query generated by WooCommerce.

add_action( 'woocommerce_product_query', 'custom_pre_get_posts_query' );

function custom_pre_get_posts_query( $q ) {

    $tax_query = (array) $q->get( 'tax_query' );

    $tax_query[] = array(
           'taxonomy' => 'product_cat',
           'field' => 'slug',
           'terms' => array( 'samples' ), 
           'operator' => 'NOT IN'
    );


    $q->set( 'tax_query', $tax_query );

}

Answer this questsion