WooCommerce: Exclude products on Shop/Listing page based to Specific Conditions

Conditions :

1. Exclude/Filter products based on meta value

I want to show products having a specific meta (e.g. Product Specification ) on listing page i.e if meta value is empty ( Product Specification is not added in CMS ) , then i want to hide it.

Solution :

Add filter “pre_get_posts” which filters the posts based on $meta_query,

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( 'meta_query',
            array(
                'relation' => 'AND',
                array(
                    'key'     => 'product_part_id',
                    'value'   => '',
                    'compare' => '!=',
                ),
                array(
                    'key'     => 'product_specification_doc',
                    'value'   => '',
                    'compare' => '!=',
                )
            )
        );

    }
    remove_action( 'pre_get_posts', 'custom_pre_get_posts_query' );
}

2. Exclude products from a particular category

Don’t display products in the knives category on the shop listing page.

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( 'knives' ),
            'operator' => 'NOT IN'
        )));
    
    }

    remove_action( 'pre_get_posts', 'custom_pre_get_posts_query' );

}
Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s