Home > Software engineering >  how to get current product category name in woocommerce
how to get current product category name in woocommerce

Time:10-29

In WooCommerce single produce page I'm using some custom fields but one tab (see attachment picture right side tab 'Residential') I'd like to get the product category, which only one will be ticked. But I'm very unsure what code is needed to get that?

Image: enter image description here

Any help to extract one product category name would be much appreciated.

The product (a property) will only have one category. Ie. Land, Residential, Commercial, Industry etc.

Thanks

Here is some code from image that's from the add_action in functions.php

    <!-- Advanced Custom Feilds-->            
<span class="property-contract-badge"><?php echo get_field('listing_status'); ?></span>
<span class="property-type-badge"><?php echo get_field('property_category'); ?></span>

<!-- Get Woocommerce product category -->        
<span class="property-type-badge"><?php echo $product->get_the_terms( $post->ID, 'product_cat'); ?></span>

CodePudding user response:

Try the below code.

<span class="property-type-badge">
    <?php   
        $terms = wp_get_post_terms( get_the_id(), 'product_cat' );
        $term  = reset($terms);
        echo $term->name;
    ?>
</span>
  • Related