Skip to content
Advertisement

Add and wrap product categories WordPress/Woocommerce in product loop

I use this snippet for display product categories in product loop on Shop and archives pages:

add_action( 'woocommerce_after_shop_loop_item_title', 'add_product_cat', 2);

function add_product_cat()
{
    global $product;
    $product_cats = wp_get_post_terms($product->id, 'product_cat');
    $count = count($product_cats);
    foreach($product_cats as $key => $cat)
    {
        echo '<span class="add_product_cat">' . $cat->name . '</span>';
    }
}

I want this:

<div class="product_cats">
    <span class="add_product_cat">Cat 1</span>
    <span class="add_product_cat">Cat 2</span>
</div>

To achieve this I use jQuery:

jQuery(function(){
    jQuery(".woocommerce li.product").each(function() {
        jQuery(this).find('span.add_product_cat').wrapAll('<div class="product_cats"></div>');
    });
});

How can I modify my PHP snippet to avoid using jQuery?

Advertisement

Answer

You could just append the corresponding tag before & after your foreach loop:

function add_product_cat()
{
    // ...
    echo '<div class="product_cats">';
    foreach($product_cats as $key => $cat)
    {
        echo '<span class="add_product_cat">' . $cat->name . '</span>';
    }
    echo '</div>';
}

Then you don’t need to custom jQuery code to wrap the contents.

User contributions licensed under: CC BY-SA
7 People found this is helpful
Advertisement