Search code examples
phpwordpresswoocommerceproductcustom-taxonomy

Replace the brand with a different category above product in WooCommerce catalog


My WooCommerce store is set up so that a product brand is displaying above the title, as in the screenshot below:

enter image description here

I've more recently set up products to display brand in their actual title. In the example above, "Bulk Goods" is set as the brand. Now that I've put it in product title, I'd like to remove it from the smaller text implementation above, and instead have that space show category. In particular, the second-tier category. All of my products have at least two categories, so I'd like the second one to appear here.

This is the code that I have been using previously to display the brand before the title:

add_action( 'woocommerce_before_shop_loop_item_title', 'aq_display_brand_before_title' );
function aq_display_brand_before_title(){
    global $product;

    $taxonomy    = 'product_brand'; // <= Here we set the correct taxonomy
    $brand_terms = get_the_terms( $product->get_id(), $taxonomy );

    // Check if it's the correct taxonomy and if there are terms assigned to the product 
    if ( $brand_terms && ! is_wp_error( $brand_terms ) ) {
        // Loop through assigned terms
        foreach( $brand_terms as $term ) {
            if ( is_a($term, 'WP_Term') ) {
                echo '<a href="' . get_term_link( $term ) . '">' . $term->name . '</a>';
            }
        }
    }
}

Solution

  • In your code, you need to replace the taxonomy from product_brand to product_cat, then you can get and display the 2nd category like:

    add_action( 'woocommerce_before_shop_loop_item_title', 'aq_display_2nd_category_before_title' );
    function aq_display_2nd_category_before_title(){
        global $product;
    
        $taxonomy  = 'product_cat'; // <= Here we set the correct taxonomy
        $cat_terms = get_the_terms( $product->get_id(), $taxonomy );
    
        // Check if it's the correct taxonomy and if there are terms assigned to the product 
        if ( $cat_terms && ! is_wp_error( $cat_terms ) ) {
            // Get the last category term
            $term = end($cat_terms);
    
            if ( is_a($term, 'WP_Term') ) {
                echo '<a href="' . get_term_link( $term ) . '">' . $term->name . '</a>';
            }
        }
    }
    

    It should work.