Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Woocommerce - Display product category above product title

I am trying to display specific categories above each of my product titles on the main shop page, the product category page, the single product page and the cart.

Using Shopfront as an example in the image below, I want to display "Nikon" above the titles of these flashes. The products are in multiple categories (Nikon, flashes, camera equipment etc.) but I only want to display the brand (Nikon) above the title. There are multiple brands within the shop (Canon, Nikon, Sony etc.) so the correct brand needs to be shown above the title depending on the maker of the product.

How can I programmatically add the "brand" category above the titles? I was thinking I could call for the categories list associated with each product within the product loop, but somehow whitelist or manually specify within the code which categories are allowed to be output on the front-end.

I have Googled pretty deep on this but can't find anything that gets me heading in the right direction.

Thanks in advance.

Existing product layout

Using suggested code to get categories, but is not working correctly yet

like image 378
coreysimons Avatar asked Dec 05 '25 14:12

coreysimons


1 Answers

This code should solve your problem.You can add this code in functions.php.I tested and confirmed its working for me.

function category_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_before_shop_loop_item_title', 'category_single_product', 25 );
like image 144
developerme Avatar answered Dec 07 '25 14:12

developerme



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!