Home > Software design >  Remove product title when product is "out of stock" on WooCommerce shop and archives pages
Remove product title when product is "out of stock" on WooCommerce shop and archives pages

Time:02-11

I am running an art gallery website using WooCommerce and the owner does not want to show the product name/title if the product has been sold/out of stock.

I have got this far with putting together a function, but it doesn't work. I wondered if anyone could give me any tips?

// Hides title on Sold products
add_filter( 'woocommerce_shop_loop_item_title', 'remove_name', 10, 2 );
function remove_name ( $product ) {
    if ( ! $product->is_in_stock()) {
        $title = '';
    }
    return $title;
}

CodePudding user response:

Your code contains some errors and mistakes:

  • woocommerce_shop_loop_item_title is NOT an filter but an action hook
  • No arguments are passed to this hook , while your code says there would be 2
  • $product is undefined, use global $product;
  • Note the else condition in my answer, otherwise the title for the current product and all subsequent products in the (shop) loop would be removed
  • Note: I've added a line with debug information, it can be removed

So you get:

function action_woocommerce_shop_loop_item_title() {
    global $product;
    
    // Is a WC product
    if ( is_a( $product, 'WC_Product' ) ) {
        // Should be removed but may be useful towards debugging
        echo '<p style="color: red; font-size: 20px;">DEBUG information: ' . $product->get_stock_status() . '</p>';
        
        // NOT in stock
        if ( ! $product->is_in_stock() ) {
            // Removes a function from a specified action hook.
            remove_action( 'woocommerce_shop_loop_item_title', 'woocommerce_template_loop_product_title', 10 );
        } else {
            add_action( 'woocommerce_shop_loop_item_title', 'woocommerce_template_loop_product_title', 10 );            
        }
    }
}
add_action( 'woocommerce_shop_loop_item_title', 'action_woocommerce_shop_loop_item_title', 9 );

CodePudding user response:

Please try to use this hook to remove product title. Use this inside the condition to check if product is in stock:

remove_action( 'woocommerce_shop_loop_item_title','woocommerce_template_loop_product_title', 10 );

CodePudding user response:

This does what you want but still allows access to the product page.

add_filter( 'woocommerce_shop_loop_item_title', function() {
    
    $product = wc_get_product( get_the_ID() );
    
    if ( ! $product->is_in_stock()) {
        remove_action( 'woocommerce_shop_loop_item_title','woocommerce_template_loop_product_title', 10 );
    }

}, 10, 2 );
  • Related