skip to Main Content

I have been trying to display the product sub-category name above the product title on the Shop or Product Archive page.

I’ve tried the code below but I am not sure how to get sub-categories instead of the category:

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>

2

Answers


  1. You can use woocommerce_single_product_summary and set priority. Try the below code. Code will go in your active theme functions.php file.

    function show_sub_category_before_title(){
    
        $terms = get_the_terms( get_the_ID(), 'product_cat' );
                         
        if ( $terms && ! is_wp_error( $terms ) ) {
         
            $product_cat = array();
         
            foreach ( $terms as $term ) {
                if( $term->parent != 0 ) {
                    $product_cat[] = $term->name;
                }
            }
                                 
            $product_cat = join( ", ", $product_cat );
            echo $product_cat;
        }
        
    }    
    add_action( 'woocommerce_single_product_summary', 'show_sub_category_before_title', 1, 1 );
    

    Tested and Works

    enter image description here

    Login or Signup to reply.
  2. you can use get_term_children() function

    $list_sub_cats = get_term_children($single_cat->term_id,'ca');
    

    I hope this will help you, Visit to get more info https://developer.wordpress.org/reference/functions/get_term_children/

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search