magmatos
magmatos

Reputation: 13

Filter products Woocommerce by ID

I am trying to change the query of the shop (archive) of Woocommerce. I searched and found a lot of snippets but didn't find my solution yet. So I hope someone here can help me out.

What I want is to hide a selection of products which are defined by a separate function. The function returns an array of product/post id's. I can't find out why this is not working...

function shop_show_products_by_id( $meta_query, $query ) {
    // Only on shop archive pages
    if( is_admin() || is_search() || ! is_shop() ) return $meta_query;

    $meta_query[] = array(
        'post__not_in' => gives_product_ids_not_to_show()
    );

    return $meta_query;
}
add_filter( 'woocommerce_product_query_meta_query', 'shop_show_products_by_id', 10, 2 );

Upvotes: 1

Views: 1240

Answers (1)

Howard E
Howard E

Reputation: 5639

post__not_in isn't a meta_query...

You can exclude products like this, using the woocommerce_product_query which is essentially pre_get_posts. If gives_product_ids_not_to_show() returns an array of integers, you can replace the array() after the post__not_in

function shop_hide_products_by_id( $q ) {
    // Only on shop archive pages
    if( is_shop() ){
        $q->set('post__not_in' , array(89,2182)); // use integers
    }
}
add_filter( 'woocommerce_product_query', 'shop_hide_products_by_id' );

Upvotes: 1

Related Questions