skip to Main Content

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;
}

3

Answers


  1. 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 );
    
    Login or Signup to reply.
  2. This does what you want but still allows access to the product page.

    add_action( 'woocommerce_shop_loop_item_title', function() {
    
        global $product;
    
        if ( ! $product->is_in_stock()) {
            remove_action( 'woocommerce_shop_loop_item_title','woocommerce_template_loop_product_title', 10 );
        }
    
    }, 5 );
    
    
    add_action( 'woocommerce_single_product_summary', function() {
    
        global $product;
        
        if ( ! $product->is_in_stock()) {
            remove_action('woocommerce_single_product_summary', 'woocommerce_template_single_title', 5);
        }
    
    }, 1);
    
    Login or Signup to reply.
  3. 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: 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 );
            }
        }
    }
    add_action( 'woocommerce_shop_loop_item_title', 'action_woocommerce_shop_loop_item_title', 9 );
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search