1
votes

I need a little help, please. I want to hide the products that are no longer in stock, only in the related products area, from single product pages. I created it and everything is ok, but I can't hide it in the related area, any changes I make don't work. Existing codes do not work in my case. Thank you.

I used these to create the "out of stock" badge:

//Add an out of stock overlay to product images when all variations are unavailable
add_action( 'woocommerce_before_shop_loop_item_title', function() {
    global $product;
    if ( !$product->is_in_stock() ) {
        echo '<span class="sold-out-overlay">Stoc epuizat</span>';
    }
});

/*Sold out badge automat in*/
.sold-out-overlay {
    background: #000000;
    color: #fff;
    font-size: 11px;
    font-weight: 600;
    padding: 5px 10px;
    position: absolute ;
    right: 5px;
    top: 20px;
    z-index: 1;
}
1
This is a nice tutorial which does what you want: rudrastyh.com/woocommerce/hide-out-of-stock-products.html - Hektor

1 Answers

1
votes

There is no need to use CSS, you can use the woocommerce_related_products filter hook instead.

function filter_woocommerce_related_products( $related_posts, $product_id, $args ) {    
    foreach( $related_posts as $key => $related_post ) {        
        // Get product
        $related_product = wc_get_product( $related_post );
        
        // Is a WC product 
        if ( is_a( $related_product, 'WC_Product' ) ) {
            // Stock status
            $stock_status = $related_product->get_stock_status();
            
            // Out of stock
            if ( $stock_status == 'outofstock' ) {
                unset( $related_posts[$key] );
            }
        }
    }
    
    return $related_posts;
}
add_filter( 'woocommerce_related_products', 'filter_woocommerce_related_products', 10, 3 );

Related: Show only “in stock” related products on WooCommerce single product page