admin管理员组

文章数量:1405516

I am trying to hide out of stock items from the Related Products section of WooCommerce. I don't want to edit theme files, so want to do this via functions.php.

I have followed this blog post, which a lot of other sites have as the solution to this problem, but it does not work properly (it simply hides out of stock products, so if there are 6 related products, and 2 are out of stock, sometimes only 2 or 3 related products will be shown on the page.

I found this post that gives a great over view of the related_proucts filters available, but it doesn't seem to want to work when I apply a meta_query to filter in stock products only.

add_filter( 'woocommerce_related_products_args', function( $args )
{
    unset( $args['meta_query'] );
    $args['meta_query'] = array(
        'key' => '_stock_status',
        'value' => 'outofstock',
        'compare' => '='
    );
    return $args;
});

Any pointers?

I am trying to hide out of stock items from the Related Products section of WooCommerce. I don't want to edit theme files, so want to do this via functions.php.

I have followed this blog post, which a lot of other sites have as the solution to this problem, but it does not work properly (it simply hides out of stock products, so if there are 6 related products, and 2 are out of stock, sometimes only 2 or 3 related products will be shown on the page.

I found this post that gives a great over view of the related_proucts filters available, but it doesn't seem to want to work when I apply a meta_query to filter in stock products only.

add_filter( 'woocommerce_related_products_args', function( $args )
{
    unset( $args['meta_query'] );
    $args['meta_query'] = array(
        'key' => '_stock_status',
        'value' => 'outofstock',
        'compare' => '='
    );
    return $args;
});

Any pointers?

Share Improve this question asked Apr 21, 2019 at 10:25 thetwopctthetwopct 2913 silver badges12 bronze badges
Add a comment  | 

1 Answer 1

Reset to default 1

Figured it out. None of the blog posts out there are accurate it seems.

Put this in your functions.php file. You can change the posts per page number to see if its working straight away or not.

add_filter( 'woocommerce_output_related_products_args', function( $args )
{
    $args = wp_parse_args( array(
        'posts_per_page' => 4,
        'meta_query' => array (
           'key' => '_stock_status',
           'value' => 'instock'
    )
    ), $args );
    return $args;
});

本文标签: How to hide out of stock products in Related Products via custom query in WooCommerce