Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Add Product category in woocommerce archive

I’m trying to add the product category inside the product card in the woocommerce archive page.
Right now it shows "Thumbnail" "Title" "Price" and "Add to cart button".

I’m using this function which should work if the variable "product" is set to the current product displayed.

My Question: Is there a way to get the queried Product in this variable?

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

Any help is appreciated.

<?php 
//Hook after product title on archive page
add_action('woocommerce_after_shop_loop_item_title','add_category');
    function add_category() {
        // set var "cardcategory"
        $cardcategory = $product->get_categories();
        // Show category and change from plural to singular
        echo '<div class="category-carousel">';

        if (strpos($cardcategory, 'Category_A_plural') !== false) {
            echo '<p class="Category_A_class">Category A singular</p>';
        }
        if (strpos($cardcategory, 'Category_B_plural') !== false) {
                echo '<p class="Category_B_class">Category B singular</p>';
        }
        echo '</div>';
    }

>Solution :

<?php 
//Hook after product title on archive page
add_action('woocommerce_after_shop_loop_item_title','add_category');

function add_category() {
    global $product; // You need to add this.

    // set var "cardcategory"
    $cardcategory = $product->get_categories();
    // Show category and change from plural to singular
    echo '<div class="category-carousel">';

    if (strpos($cardcategory, 'Category_A_plural') !== false) {
        echo '<p class="Category_A_class">Category A singular</p>';
    }
    if (strpos($cardcategory, 'Category_B_plural') !== false) {
            echo '<p class="Category_B_class">Category A singular</p>';
    }
    echo '</div>';
}

You need to add the line global $product as shown above. $product is an instance of WC_Product, I believe Woocommerce uses WordPress’ the_post() functionality under the hood to set this variable but I’m not 100% sure.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading