简体   繁体   中英

Add product category link on WooCommerce single product page

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; ?> <?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 );

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" class="product_category_title">';
        
        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 );

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM