Search code examples
phpwordpresswoocommerceproducttaxonomy-terms

Add Product brand taxonomy term above product title in WooCommerce


I would like to use the Woocommerce taxonomy " Brands " to show the product brand above the product title on shop page and product page.

I add this code to functions.php, it is working, however the brand text is linking to the brand page and both shop page and product page. I would like to disable the brand url link on shop page and keep it only for product page.

Can someone help ?

function product_brand() {
    $terms = wp_get_post_terms(get_the_ID(), 'product_brand');
    if (!is_wp_error($terms) && !empty($terms)) {
        $term = $terms[0];
        $class = esc_attr( $term->slug );
        $url = esc_url( get_term_link( $term ) );
        $name = esc_html( $term->name );
        echo "<div class=\"product_brand $class\"><a href=\"$url\">$name</a></div>";
    }
}

add_action( 'woocommerce_shop_loop_item_title', 'product_brand', 10);

add_action( 'woocommerce_single_product_summary', 'product_brand', 5);

Solution

  • You should better use get_the_terms() which is cached instead of wp_get_post_terms(), avoiding multiple heavy queries.

    Then you can use the term link only on single product pages targeting the related hook.

    Try the following:

    // Common utility function to get the product brand term object
    function get_the_brand_term() {
        $terms = get_the_terms(get_the_ID(), 'product_brand');
    
        return $terms && !is_wp_error($terms) ? reset($terms) : false;
    }
    
    // On loop product archives (just the term)
    function single_product_brand() {
        if ( $term = get_the_brand_term() ) {
            printf('<div class="product_brand %s"><a href="%s">%s</a></div>',
            esc_attr($term->slug), esc_url( get_term_link($term) ), esc_html($term->name) );
        }
    }
    add_action( 'woocommerce_single_product_summary', 'single_product_brand', 10 );
    
    // On single product pages (linked term)
    function loop_product_brand() {
        if ( $term = get_the_brand_term() ) {
            printf('<div class="product_brand %s">%s</div>',
            esc_attr($term->slug), esc_html($term->name) );
        }
    }
    add_action( 'woocommerce_shop_loop_item_title', 'loop_product_brand', 5 );
    

    It should work.


    Edit:

    CSS styling for loop archives and single product pages.

    Replace:

    .product_brand a { font-size: 13px; font-weight: bold; }
    

    with:

    .product_brand, .product_brand a { font-size: 13px; font-weight: bold; }