When you first set up your WooCommerce store, you will need to decide how to organize your products. One way to do this is by using categories and subcategories.
This will help your customers find the products they are looking for more easily.
To set up categories and subcategories, go to WooCommerce > Products > Categories. Here, you can add new categories and subcategories.
You can also drag and drop to rearrange them. Once you have your categories and subcategories set up the way you want, click Save Changes.
Now that you have your categories and subcategories set up, you need to decide how you want them to be displayed on your website. To do this, go to WooCommerce > Settings > Products. Under the General tab, there is an option for Default Category Display.
Here, you can choose whether you want your categories and subcategories to be displayed in a dropdown menu, as a list, or not at all. Select the option that you prefer and click Save Changes.
Your categories and subcategories are now set up and ready to be used on your WooCommerce store!
If you are using a WooCommerce theme, it is likely that your theme already has a built-in way to display a category and subcategory. However, if you are using a theme that does not have this feature, you can use the following code to display a category and subcategory in WooCommerce. This code should be placed in your child theme’s functions.php file:
add_action( 'woocommerce_after_shop_loop_item_title', 'woocommerce_template_loop_category', 10 );
function woocommerce_template_loop_category() {
global $product;
$categories = get_the_terms( $product->get_id(), 'product_cat' );
if ( !empty( $categories ) ) {
echo '<div class="product-categories">';
foreach( $categories as $category ) {
echo '<a href="' . get_term_link( $category->term_id ) . '">' . $category->name . '</a>';
}
echo '</div>';
}
}
This code uses the woocommerce_after_shop_loop_item_title action hook to display the categories and subcategories after the title of each product in the shop loop. The global $product variable is used to get the product’s categories, and the get_the_terms() function is used to retrieve the categories and subcategories. The code then loops through the categories and subcategories and displays them as links.