Jeff
Jeff

Reputation: 137

Exclude specific products from everywhere with a meta query in Woocommerce

I would like to exclude products from a given city from my shop page but also from my home page where I display products from the flatsome UX Builder's woocommerce shop widget (not sure it's a widget).

The product with the given city doesn't appear in my shop page, but they still appear in my home page.

add_filter( 'pre_get_posts', 'custom_pre_get_posts_query' );
function custom_pre_get_posts_query( $q ) {
    if ($q->is_main_query())
    {
        $meta_query = $q->get('meta_query');
        $meta_query[] = array(
            'key'=>'city',
            'value' => 'Cassis',
            'compare'=>'NOT EXISTS',
            );
        $q->set('meta_query',$meta_query);

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

Any idea?

Upvotes: 4

Views: 1977

Answers (1)

LoicTheAztec
LoicTheAztec

Reputation: 254483

Instead of using pre_get_posts filter hook for a meta_query on products loop, you could use the dedicated woocommerce_product_query_meta_query filter hook.

Now for your problem it could be a widgets or a shortcode that is used, so there is also some dedicated hooks for them.

As the meta_query is going to be similar for the 3 hooked functions, you can set it in a custom function and call it in the 3 hooked functions this way:

// The meta query in a function
function custom_meta_query( $meta_query ){
    $meta_query[] = array(
        'key'=>'city',
        'value' => 'Cassis',
        'compare'=>'NOT EXISTS',
    );
    return $meta_query;
}

// The main shop and archives meta query
add_filter( 'woocommerce_product_query_meta_query', 'custom_product_query_meta_query', 10, 2 );
function custom_product_query_meta_query( $meta_query, $query ) {
    if( ! is_admin() )
        return custom_meta_query( $meta_query );
}

// The shortcode products query
add_filter( 'woocommerce_shortcode_products_query', 'custom__shortcode_products_query', 10, 3 );
function custom__shortcode_products_query( $query_args, $atts, $loop_name ) {
    if( ! is_admin() )
        $query_args['meta_query'] = custom_meta_query( $query_args['meta_query'] );
    return $query_args;
}

// The widget products query
add_filter( 'woocommerce_products_widget_query_args', 'custom_products_widget_query_arg', 10, 1 );
function custom_products_widget_query_arg( $query_args ) {
    if( ! is_admin() )
        $query_args['meta_query'] = custom_meta_query( $query_args['meta_query'] );
    return $query_args;
}

Code goes in function.php file of the active child theme (or active theme).

This should work…

Upvotes: 2

Related Questions