'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'



Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source