Home > other >  Apply custom badge to specific product id on archive loop item WooCommerce
Apply custom badge to specific product id on archive loop item WooCommerce

Time:05-24

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

Yet I have tried to add_action before_shop_loop_item but the problem is that the $product variable does not contain the object. I was thinking of $product->get_id() and if it matches the product id to 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>';
    }
} 

BTW get_id() cannot executed because $product looks like empty. So that's where I stack.

Yeah, and the location I want to print the HTML is woocommerce_before_shop_loop_item - right before the sales badge.

Any suggestions on how to filter through loop items?

CodePudding user response:

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

Use global $product instead

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 '<script>console.log("add_custom_badge")</script>';
        }
    }
}
add_action( 'woocommerce_before_shop_loop_item', 'action_woocommerce_before_shop_loop_item', 10 );
  • Related