58
A client of mine has a category called “Brand”. Each product is assigned to a specific Brand subcategory e.g. Nike, Adidas, etc. The goal of this task was to show the “Brand” subcategories in the shop/category/loop pages as a way to help the user identify the brand name.
The same can be applied to showing ALL categories, so the user knows exactly to what section of the shop the product belong to. Great, let’s see how it’s done!
PHP Snippet 1: Show Category Name/s @ WooCommerce Shop Items
/**
* @snippet WooCommerce Show Product Categories
* @how-to Get tutoraspire.com FREE
* @author Tutor Aspire
* @compatible WooCommerce 5.1
* @donate $9 https://tutoraspire.com
*/
add_action( 'woocommerce_after_shop_loop_item_title', 'tutoraspire_show_all_subcats', 2 );
function tutoraspire_show_all_subcats() {
global $product;
$cats = get_the_terms( $product->get_id(), 'product_cat' );
if ( empty( $cats ) ) return;
echo join( ', ', wp_list_pluck( $cats, 'name' ) );
}
PHP Snippet 2: Show Subcategory Name/s @ WooCommerce Shop Items
/**
* @snippet WooCommerce Show Product Subcategories
* @how-to Get tutoraspire.com FREE
* @author Tutor Aspire
* @compatible WooCommerce 5.1
* @donate $9 https://tutoraspire.com
*/
add_action( 'woocommerce_after_shop_loop_item_title', 'tutoraspire_show_all_subcats', 2 );
function tutoraspire_show_all_subcats() {
global $product;
$cats = get_the_terms( $product->get_id(), 'product_cat' );
if ( empty( $cats ) ) return;
foreach ( $cats as $term ) {
// If parent cat ID = 116 echo subcat name...
if ( $term->parent == 116 ) {
echo $term->name;
}
}
}