Search code examples
wordpresswoocommercewordpress-themingwordpress-shortcodewoocommerce-theming

How to hide products from the products shortcode 'woocommerce_shortcode_products_query' using product ids


I am using the woocommerce products shortcode to show some related products on a product page.

The product shortcode is as follows:

do_shortcode('[products limit="6" columns="6"]');

I am modifying the shortcode using the woocommerce_shortcode_products_query filter like so:

add_filter( 'woocommerce_shortcode_products_query', function( $query_args, $atts, $loop ){

    $product_id = 12345;

    // Remove out of stock results
    $query_args['meta_query'] = array( array(
        'key'     => '_stock_status',
        'value'   => 'outofstock',
        'compare' => 'NOT LIKE',
    ) );

    // Remove the current product by id
    $query_args['tax_query'] = array( array(
        'taxonomy' => 'product', 
        'field' => 'id', 
        'terms' => array($product_id), // Remove this product from the shortcode results
        'operator' => 'NOT IN',
    ) );


    
    return $query_args;

}, 10, 3);

The first part works by removing the out of stock results.

The second part does not work and I am unable to work out how to exclude a specific product from the query.

All results from google when searching the problem are talking about product_cat taxonomies, however I do not want to remove products in a category, I want to remove the current product by id so that only other related products show in the shortcode.

So my question: How do you hide the current product from the products shortcode using 'woocommerce_shortcode_products_query'


Solution

  • You would need to use the 'post__not_in' argument of the WP_Query.

    So your code would be something like this:

    add_filter('woocommerce_shortcode_products_query', function ($query_args, $atts, $loop) {
    
        $product_ids = array(1, 2, 3);
    
        $query_args['meta_query'] = array(array(
            'key'     => '_stock_status',
            'value'   => 'outofstock',
            'compare' => 'NOT LIKE',
        ));
    
        $query_args['post__not_in'] = $product_ids;
    
    
        return $query_args;
    }, 10, 3);
    

    This will exclude products with the ids of 1, 2 and 3. You could pass different product ids to the $product_ids variable.

    You could exclude only one product as well, by just passing one single id to the $product_ids variable! (e.g. $product_ids = array(37))