WooCommerce: How to Echo Product Category – A Beginner’s Guide
So, you’re building a stunning WooCommerce store and want to display the product category on your product pages, archive pages, or even in custom locations? Great! Knowing how to “echo” (basically, display) the product category is a fundamental skill for WooCommerce customization. This guide will walk you through the process, making it easy for even beginners to get started.
Why Echo Product Categories?
Imagine you’re browsing an online clothing store. Wouldn’t it be helpful to see the category (“Shirts”, “Pants”, “Dresses”) prominently displayed on each product page? That’s the power of echoing product categories! Here are some reasons why you might want to display them:
- Improved User Experience: Helps customers understand where they are in your store’s hierarchy.
- Better Navigation: Provides a clear path for customers to explore related products.
- SEO Benefits: Can improve search engine visibility by including relevant category keywords.
- Enhanced Design: Adds visual appeal and context to your product listings.
- Personalized Marketing: You can use the category information to show related promotions or up-selling opportunities. For example, if a customer is viewing a “Running Shoes” product, you could show them “Running Socks” or “Running Apparel”.
The Basics: Understanding Product Categories in WooCommerce
WooCommerce uses taxonomies to categorize products. Think of a taxonomy as a fancy word for a system of classifying things. The most common taxonomy for products is `product_cat` (product category). We’ll use this taxonomy to retrieve and display the category information.
Method 1: Using the `wc_get_product_terms()` Function
This is generally the preferred and most flexible method. `wc_get_product_terms()` retrieves the terms (categories) associated with a product. Here’s how you can use it:
<?php global $product; // Ensures you have access to the $product object
if ( $product ) {
$terms = wc_get_product_terms( $product->get_id(), ‘product_cat’, array( ‘orderby’ => ‘name’, ‘order’ => ‘ASC’ ) );
if ( $terms && ! is_wp_error( $terms ) ) {
echo ‘
echo ‘Category: ‘; // Optional: Add a label
foreach ( $terms as $term ) {
echo ‘‘ . esc_html( $term->name ) . ‘‘;
}
echo ‘
‘; // Close the container
}
}
?>
Let’s break down what’s happening:
1. `global $product;`: This line is crucial. It makes the `$product` object (which contains all the information about the current product) available to your code. If you’re inside the main WooCommerce loop (like on a single product page), `$product` is usually already available, but it’s good Discover insights on Woocommerce Subscriptions How To End practice to include this line.
2. `if ( $product ) { … }`: This checks if a `$product` object exists. This prevents errors if the code runs outside of a product context.
3. `$terms = wc_get_product_terms( $product->get_id(), ‘product_cat’, array( ‘orderby’ => ‘name’, ‘order’ => ‘ASC’ ) );`: This is the core of the code. It uses the `wc_get_product_terms()` function:
- `$product->get_id()`: Gets the ID of the current product.
- `’product_cat’`: Specifies the taxonomy we’re interested in (product categories).
- `array( ‘orderby’ => ‘name’, ‘order’ => ‘ASC’ )`: Optional arguments to control the order of the returned categories (here, ordered alphabetically in ascending order).
4. `if ( $terms && ! is_wp_error( $terms ) ) { … }`: This checks if categories were found and that there were no errors retrieving them.
5. `echo ‘
6. `echo ‘Category: ‘;`: This adds a simple “Category:” label before the categories are displayed.
7. `foreach ( $terms as $term ) { … }`: This loops through each category (`$term`) found for the product.
- `echo ‘‘ . esc_html( $term->name ) . ‘‘;`: This creates a link to the category archive page.
- `esc_url( get_term_link( $term ) )`: Gets the URL of the category page and sanitizes it for security.
- `esc_html( $term->name )`: Gets the name of the category and escapes it for security (prevents malicious code from being injected).
Method 2: Using the `get_the_terms()` Function (Less Recommended)
While `get_the_terms()` can also retrieve product categories, it’s generally less suitable for WooCommerce development. `wc_get_product_terms()` is specifically designed for WooCommerce and provides better compatibility. However, let’s see how it works for completeness:
<?php global $product;
if ( $product ) {
$terms = get_the_terms( $product->get_id(), ‘product_cat’ );
if ( $terms && ! is_wp_error( $terms ) ) {
echo ‘
echo ‘Category: ‘;
foreach ( $terms as $term ) {
echo ‘‘ . esc_html( $term->name ) . ‘‘;
}
echo ‘
‘;
}
}
?>
The main difference here is the use of `get_the_terms()` instead of `wc_get_product_terms()`. The rest of the code is largely the same.
Where to Put the Code
The best place to add this code depends on where you want the categories to appear:
- Single Product Page: You can add this code to your theme’s `single-product.php` file. Important: Never directly edit your theme’s files! Instead, create a child theme and modify the `single-product.php` file in your child theme. This protects your changes when the parent theme is updated. Alternatively, you can use a WooCommerce hook.
- Archive Pages (Category/Shop Pages): You might need to modify your theme’s `archive-product.php` or `content-product.php` (again, using a child theme). The exact file depends on your theme’s structure.
- Custom Locations: For custom locations (like a specific widget area or page template), you can directly add the code to your theme’s files (again, preferably within a child theme or using a custom plugin).
Using WooCommerce Hooks (Recommended for Single Product Pages)
A cleaner and more robust approach is to use WooCommerce hooks. Hooks allow you to insert your code at specific points in the WooCommerce template structure without directly modifying the template files.
Here’s an example of using the `woocommerce_single_product_summary` hook to display the categories after the product title:
<?php /**
function display_product_category_after_title() {
global $product;
if ( $product ) {
$terms = wc_get_product_terms( $product->get_id(), ‘product_cat’, array( ‘orderby’ => ‘name’, ‘order’ => ‘ASC’ ) );
if ( $terms && ! is_wp_error( $terms ) ) {
echo ‘
echo ‘Category: ‘;
foreach ( $terms as $term ) {
echo ‘‘ . esc_html( $term->name ) . ‘‘;
}
echo ‘
‘;
}
}
}
?>
Explanation:
1. `add_action( ‘woocommerce_single_product_summary’, ‘display_product_category_after_title’, 6 );`: This line adds your custom function `display_product_category_after_title` to the `woocommerce_single_product_summary` hook. The `6` is the priority; lower numbers run earlier. You might need to adjust the priority to position the categories exactly where you want them.
2. `function display_product_category_after_title() { … }`: This is your custom function that contains the code to retrieve and display the categories. It’s the same code as in Method 1.
Where to put this code: Place this code in your theme’s `functions.php` file (again, in your child theme’s `functions.php`!).
Important Considerations
- Security: Always use `esc_url()` and `esc_html()` to sanitize your output and prevent security vulnerabilities.
- Child Themes: As mentioned earlier, always use a child theme when modifying your theme’s files. This prevents your changes from being overwritten when the parent theme is updated.
- Custom Styling: Use CSS to style the categories to match your store’s design. The provided examples wrap the output in a `
` with the class `product-categories`, making it easy to target with CSS.
- WooCommerce Updates: Keep your WooCommerce installation and themes updated to ensure compatibility and security.
- Testing: Thoroughly test your code after making any changes to ensure it works as expected and doesn’t break your store.
- Plugin Conflict: Sometimes other plugins will modify the display of the category and product archive pages, be mindful of any plugin conflicts when modifying product Learn more about How To Get Rid Of Related Products In Woocommerce pages or archive pages, and try disabling plugins and retesting.
Conclusion
Displaying product categories effectively enhances the user experience and helps customers navigate your WooCommerce store with ease. By understanding the techniques outlined in this guide and following best practices, you can confidently customize your store and create a seamless shopping experience for your customers. Remember to always prioritize security, use child themes, and thoroughly test your code. Happy coding!