Skip to content
Advertisement

Remove out of stock products from WooCommerce related products custom WP query

hello I want to show related products based on my custom query but I just want to show ‘in_stocks’ products and meta_query not working with tax_query. anyone can help me?

 $query_args = array(
    'posts_per_page' => 10,
    'no_found_rows'  => 1,
    'post__not_in' => array( $product->get_id()),
    'post_status'    => 'publish',
    'post_type'      => 'product',
     
            'tax_query'      => array(
                'relation'      => 'OR',
                 array(
                     'taxonomy'     => 'product_cat',
                     'field'        => 'id',
                     'terms'        => $cats_array
                 ),
                array(
                    'taxonomy'     => 'product_tag',
                    'field'        => 'id',
                    'terms'        => $tags_array
                ) )
    );

Advertisement

Answer

To remove out of stock products from your custom WP query, you need to add an additional array to tour tax query as follows:

$query_args = array(
    'posts_per_page' => 10,
    'no_found_rows'  => 1,
    'post__not_in'   => array( $product->get_id() ),
    'post_status'    => 'publish',
    'post_type'      => 'product',
    'tax_query'      => array(
        'relation' => 'AND',
        array(
            'taxonomy' => 'product_visibility',
            'field'    => 'name',
            'terms'    => array('outofstock'),
            'operator' => 'NOT IN'
        ),
        array(
            'relation' => 'OR',
            array(
                'taxonomy'     => 'product_cat',
                'field'        => 'id',
                'terms'        => $cats_array
            ),
            array(
                'taxonomy'     => 'product_tag',
                'field'        => 'id',
                'terms'        => $tags_array
            )
        )
    ),
);

Or also maybe using a meta query this way:

$query_args = array(
    'posts_per_page' => 10,
    'no_found_rows'  => 1,
    'post__not_in'   => array( $product->get_id() ),
    'post_status'    => 'publish',
    'post_type'      => 'product',
    'tax_query'      => array(
        'relation' => 'OR',
        array(
            'taxonomy'     => 'product_cat',
            'field'        => 'id',
            'terms'        => $cats_array
        ),
        array(
            'taxonomy'     => 'product_tag',
            'field'        => 'id',
            'terms'        => $tags_array
        )
    ),
    'meta_query'    => array(
        'key'     => '_stock_status',
        'value'   => 'outofstock',
        'compare' => '!='
    )
);

It should work.

Related: Show only WooCommerce in stock products with a WP_Query

User contributions licensed under: CC BY-SA
10 People found this is helpful
Advertisement