Support » Plugin: WooCommerce » pre_get_posts and Layered Nav Filter widget compatibility issue

  • This is link to dev website: https://beta.projectswatches.com/?filter_color=aqua
    it has Layered Nav filters enabled for custom attributes, and it has custom code in functions.php of active theme:

    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( 'watch-archives-category', 'gift-cards' ), // Don't display products in the archive category on the shop page
    			'operator' => 'NOT IN'
    		)));
    
    	}
    	remove_action( 'pre_get_posts', 'custom_pre_get_posts_query' );
    
    }

    I got this code from this page: https://docs.woocommerce.com/document/exclude-a-category-from-the-shop-page/

    The theme itself doesn’t have any other modifications. All plugins are deactivated exept for woocommerce. All components – wordpress, woocommerce, theme – all latest version.
    The problem is: the Layered Nav attribute filter doesn’t work along with pre_get_post snippet. You may choose attributes from filter, but page will still showing all products.
    The question is: how to make it work properly? Is this a woocommerce bug?

Viewing 3 replies - 1 through 3 (of 3 total)
  • On my site I have exactly the same problem. Without pre_get_posts everything works normal. I hope we will find a solution soon.

    I also have this problem. I’m using a pre_get_posts tax_query to exclude a category with the NOT IN operator, but this breaks the wc layered nav filters.

    I had solve this problem by editing woocommerce files directly. Not best, but working.
    Go to \includes\class-wc-query.php and search for

    		if ( ! is_array( $tax_query ) ) {
    			$tax_query = array( 'relation' => 'AND' );
    		}

    – it is around line #549 and replace it with code:

            if ( ! is_array( $tax_query ) AND ! is_tax('product_cat') ) {
                $tax_query = array( 'relation' => 'AND', array(
                    'taxonomy' => 'product_cat',
                    'field' => 'slug',
                    'terms' => array( 'SLUG_OF_CATEGORY', 'COMMA_SEPARETAD' ),
                    'operator' => 'NOT IN'
                ) );
    		}

    change categories slugs to required.
    You have to edit this file manually after every woocommerce update.

    • This reply was modified 2 months, 1 week ago by  romapad.
Viewing 3 replies - 1 through 3 (of 3 total)
  • You must be logged in to reply to this topic.