Woocommerce related products - only show in stock related products
Asked Answered
T

2

2

I'm trying to filter the products shown in "related products" in woocommerce so that it only outputs related products that are in stock.

I've tried editing the "related.php" template as below - but it ain't working!

$args = apply_filters( 'woocommerce_related_products_args', array(
    'post_type'            => 'product',
    'ignore_sticky_posts'  => 1,
    'no_found_rows'        => 1,
    'posts_per_page'       => $posts_per_page,
    'orderby'              => $orderby,
    'post__in'             => $related,
    'post__not_in'         => array( $product->id ),
    'meta-key'             => '_stock_status',
    'meta-value'           => 'outofstock',
    'compare'              => '!='
) );

I'd appreciate any help

Many thanks

Tootle answered 30/3, 2015 at 17:39 Comment(0)
P
10

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.

Pasteup answered 1/4, 2020 at 18:51 Comment(1)
It creates below error. Uncaught Error: Call to a member function is_in_stock() on bool inTallyman
B
0

I think You have done this task, but if anyone having this issue then they can use this code to show only "in stock" product on related products, change into related.php:

$args = apply_filters( 'woocommerce_related_products_args', array(

  'post_type'            => 'product',
  'ignore_sticky_posts'  => 1,
  'no_found_rows'        => 1,
  'posts_per_page'       => $posts_per_page,
  'orderby'              => $orderby,
  'post__in'             => $related,
  'post__not_in'         => array( $product->id ),
  'meta_key'             => '_stock_status',
  'meta_value'           => 'instock',
  'compare'              => '!='
)
);
Bunder answered 6/11, 2015 at 9:3 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.