p_e_88
p_e_88

Reputation: 1037

Echo category name in woocommerce

I would like to change the Text of the related products, which is at the end of the product detail page. At the moment I'm displaying This could be interesting by using this code

<h2><?php esc_html_e( 'This could be interesting', 'woocommerce' ); ?></h2>

What I would like to display is Our favorite category name

I tried to expand the code with this snippet, without any success

<?php echo wc_get_product_category_list($product->get_id()) ?>

How is it possible to get this function done?

Upvotes: 1

Views: 1350

Answers (1)

Saqib Amin
Saqib Amin

Reputation: 1171

Here is a little helper function that you could put in your functions.php

function get_favorite_category_title_for( $product_id ) {
    $title = __('This could be interesting', 'woocommerce');

    $cats = wp_get_post_terms( $product_id, 'product_cat' );
    if( count($cats) > 0 ) {
        $title = __( 'Our favorite ', 'woocommerce' ) . $cats[0]->name;
    }

    return $title;
}

and then replace the h2 tag with:

<h2><?php echo get_favorite_category_title_for( get_queried_object_id() ); ?></h2>

you can change get_queried_object_id with the $product->get_id() if you have access to $product object.

Upvotes: 2

Related Questions