Home  >  Q&A  >  body text

Customize badges for specific product IDs on WooCommerce archive loop items

I'm trying to display a badge with "Exclusive" text to a specific product in the store page or category archive or whenever this specific product cycle item is shown.

But I tried adding _action before _shop_loop_item, but the problem is that the $product variable does not contain the object. I'm thinking of $product->get_id() and if it matches the product id, apply some HTML to that specific product loop item.

add_action('woocommerce_before_shop_loop_item', 'add_custom_badge', 1);

function add_custom_badge( $product ) {
    if ( $product->get_id() === 123 ) {
        echo '<script>console.log("add_custom_badge")</script>';
    }
} 

By the way, get_id() cannot be executed because $product appears to be empty. This is where I stack up.

Yes, the location where I want the HTML to be printed is woocommerce_before_shop_loop_item - just before the sales badge.

Any suggestions on how to filter loop items?

P粉087074897P粉087074897268 days ago347

reply all(1)I'll reply

  • P粉718165540

    P粉7181655402024-02-18 11:58:24

    By default,

    $product is not passed to the callback function at the woocommerce_before_shop_loop_item hook. That's why it doesn't work

    Use insteadglobal $product

    So you get:

    function action_woocommerce_before_shop_loop_item() {
        global $product;
    
        // Is a WC product
        if ( is_a( $product, 'WC_Product' ) ) {
            if ( $product->get_id() == 123 ) {
                echo 'sssccc';
            }
        }
    }
    add_action( 'woocommerce_before_shop_loop_item', 'action_woocommerce_before_shop_loop_item', 10 );
    

    reply
    0
  • Cancelreply