Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Hide out of stock related products in WooCommerce

In WooCommerce I would like to hide Out of Stock products from Related products in single product pages. Is it possible?

Any track is appreciated.

like image 796
sarah miller Avatar asked Dec 23 '22 00:12

sarah miller


1 Answers

None of the answers given here worked for me (I believe the woocommerce_output_related_products_args filter mentioned does not accept meta_queries), and I wanted a solution that didn't use an SQL query, so I put together the solution below:

add_filter( 'woocommerce_related_products', 'mysite_filter_related_products', 10, 1 );
function mysite_filter_related_products( $related_product_ids ) {

    foreach( $related_product_ids as $key => $value ) {
        $relatedProduct = wc_get_product( $value );
        if( ! $relatedProduct->is_in_stock() ) {
            unset( $related_product_ids["$key"] );
        }
    }

    return $related_product_ids;
}

Hope that helps someone looking for a similar solution.

like image 132
dmoz Avatar answered Jan 09 '23 04:01

dmoz