Home > database >  Add product category link on WooCommerce single product page
Add product category link on WooCommerce single product page

Time:11-03

This code is outputting the Product (Brand) Category in (almost) the right spot - above the product title - on the Single Product Page.

How can I hyperlink it (Product Category) to the Product Category page? I essentially need to make this <?php echo $single_cat->name; ?> a dynamic hyperlink.

/** Output Product (Brand) Category on single product page **/
function add_brand_category(){

  $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 ); ?>
      <h3 itemprop="name" class="product_category_title"><span><?php echo $single_cat->name; ?></span></h3>
<?php }
}
add_action( 'woocommerce_single_product_summary', 'add_brand_category', 2 );

CodePudding user response:

You can use wc_get_product_category_list() – which returns the product categories in a list adding a hyperlink to the product category page.

So you get:

function action_woocommerce_single_product_summary() {
    global $product;
    
    // Is a WC product
    if ( is_a( $product, 'WC_Product' ) ) {
        echo '<h3 itemprop="name" >';
        
        echo wc_get_product_category_list( $product->get_id(), ', ', '<span>' . _n( 'Category:', 'Categories:', count( $product->get_category_ids() ), 'woocommerce' ) . ' ', '</span>' ); 
        
        echo '</h3>';
    }
}
add_action( 'woocommerce_single_product_summary', 'action_woocommerce_single_product_summary', 2 );
  • Related