Customize badges for specific product IDs on WooCommerce archive loop items
P粉087074897
P粉087074897 2024-02-17 13:54:07
0
1
349

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粉087074897
P粉087074897

reply all(1)
P粉718165540

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 );
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!