WooCommerce – how to display product category above product?

The question:

I’m a newbie at modifying wooCommerce.
I hope someone can help me with a problem i’m having while trying to make a minor change to the plugin to fit with a request from my client.

I’m trying to modify WooCommerce to display the category name for each product. I want the category name to be shown above the product image on the main shop page.
(the view where many products are shown on the screen at once)

I’ve searched around, and i can’t seem to find how to call the product->category to get the category name for each product being shown.

In the wooCommerce files, i’ve found content-product.php
(in templates/content-product.php)

and i’d like to inject the category for each product by adding to this action:
do_action( 'woocommerce_before_shop_loop_item_title' );

I understand that I can add a function in my theme’s functions.php to inject some new code into the ”woocommerce_before_shop_loop_item_title’

but I can’t work out how to get the category for each product.

can someone help? or tell me where i might be able to find the answer?

any help will be much appreciated, thank you!

The Solutions:

Below are the methods you can try. The first solution is probably the best. Try others if the first one doesn’t work. Senior developers aren’t just copying/pasting – they read the methods carefully & apply them wisely to each case.

Method 1

The product title is added to the woocommerce_single_product_summary hook at priority 5, so you’ll want to add to the same hook with a lower (earlier) priority. You’d add this to your theme’s functions.php file. I presume when you say “category” you mean the WooCommerce product category, so this should return the first one and print it before the product title:

function wpa89819_wc_single_product(){

    $product_cats = wp_get_post_terms( get_the_ID(), 'product_cat' );

    if ( $product_cats && ! is_wp_error ( $product_cats ) ){

        $single_cat = array_shift( $product_cats ); ?>

        <h2 itemprop="name" class="product_category_title"><span><?php echo $single_cat->name; ?></span></h2>

<?php }
add_action( 'woocommerce_single_product_summary', 'wpa89819_wc_single_product', 2 );

Method 2

you need the get_categories function, which takes the following arguments:

get_categories( $separator, $before, $after )

so in it’s simples form (assuming only one category per product), just add <?php echo $product->get_categories(); ?> to your content-product.php (line 53).
If you have more categories, you can do it like on the single product page:

<?php echo $product->get_categories( ', ', '<span class="posted_in">' . _n( 'Category:', 'Categories:', sizeof( get_the_terms( $post->ID, 'product_cat' ) ), 'woocommerce' ) . ' ', '.</span>' ); ?>

All methods was sourced from stackoverflow.com or stackexchange.com, is licensed under cc by-sa 2.5, cc by-sa 3.0 and cc by-sa 4.0

Leave a Comment