Get WooCommerce product categories from WordPress

Get WooCommerce product categories from WordPress

  1. Blog
  2. 15 November 2026
  3. 4 min read

Stefan Bogdanescu

Founder & Senior Architect

Fetching WooCommerce Product Categories Without Querying Products

When building a custom loop in a WordPress theme, it is tempting to treat WooCommerce as if it were just another set of posts. You might initialize a WP_Query to fetch products and then attempt to retrieve category data using standard WordPress functions like get_categories(). While this works for generic post categories, it fails specifically for WooCommerce product categories because of how the plugin registers its taxonomy.

In your current setup, you are passing a specific category slug via $atts[0] to the query arguments. However, calling get_categories() inside the loop without context will return all registered categories across the entire site, not just those associated with the products currently being iterated. Furthermore, because get_categories() expects global state or explicit arguments, passing it directly into a string concatenation often results in the function returning an unformatted array that breaks your HTML output.

To display the correct category information for your specific product loop, you must leverage the WooCommerce-specific taxonomy functions. The most reliable method is to use wc_get_product_category() or its plural counterpart wc_get_product_categories(). These functions are designed to handle the underlying data structure of the product_cat taxonomy correctly.

You can determine the appropriate function by checking the number of categories assigned to a product. Use wc_get_product_category('your-category-slug') if you are working with a single category, or iterate through wc_get_product_categories('your-category-slug') if a product belongs to multiple groups. These functions return either a string (for a single category) or an array of strings (for multiple categories), which fits much better into your HTML generation logic than the raw output of get_categories().

Here is how you can refactor the loop to dynamically inject the correct category names:

function get_me_list_of($atts, $content = null) {   
    // Extract the category slug passed in the shortcode/attribute
    $target_cat = isset($atts[0]) ? $atts[0] : '';

    // Query products within the specific category
    // Note: If using 'product_cat' => $target_cat, ensure the slug is exact.
    $args = array( 
        'post_type' => 'product', 
        'posts_per_page' => 10, 
        'tax_query' => array(
            array(
                'taxonomy' => 'product_cat',
                'field'    => 'slug',
                'terms'    => $target_cat
            )
        )
    );

    $loop = new WP_Query( $args );

    echo '<h1 class="upp">Style ' . esc_attr($target_cat) . '</h1>';
    echo "<ul class='mylisting'>";

    while ( $loop->have_posts() ) : 
        $loop->the_post(); 
        global $product; 

        if ($product && $product->get_id()) {
            // Check for single or multiple categories
            $single_cat = wc_get_product_category('', true);
            
            // If wc_get_product_category returns false (no single category found), use the array version
            if (!$single_cat) {
                $cats_array = wc_get_product_categories();
                $cat_list = !empty($cats_array) ? implode(', ', $cats_array) : 'Uncategorized';
            } else {
                $cat_list = esc_html($single_cat);
            }

            echo '<li><a href="' . get_permalink() . '">' . get_the_post_thumbnail($loop->post->ID, 'thumbnail') . '</a></li>';
            echo '<li><a href="' . get_permalink() . '">' . esc_html($loop->post->post_title) . '</a></li>';
            echo '<li><a href="#">' . $cat_list . '</a></li>';
        }
    endwhile; 

    echo "</ul>";

    wp_reset_query(); 
}

Handling Multiple Categories and Data Safety

One common pitfall when working with WooCommerce loops is assuming that every product has a category assigned. By default, products often fall back to an "Uncategorized" term if no specific category is selected in the admin panel. When using wc_get_product_category(), it returns an empty string if no single primary category exists, rather than throwing an error, but relying solely on this can leave your UI blank.

The code snippet above checks whether a single category was returned first. If not, it falls back to fetching all associated categories and joining them with commas. This ensures that your list item always contains text, preventing layout shifts caused by empty <a> tags.

Additionally, always use esc_html() or esc_attr() when echoing data into HTML attributes or the body. Since $atts[0] comes directly from a shortcode argument, it is untrusted input. Passing raw user input into an href attribute or displaying it as text without sanitization opens your site to XSS vulnerabilities.

Why Avoid Generic Functions?

While get_the_terms() can also retrieve terms for a post, it requires you to specify the taxonomy explicitly: get_the_terms($post_id, 'product_cat'). This returns an array of WP_Term objects. To convert these into a clean string list, you would need to extract the $term->name property from each object and implode them. While valid, this adds boilerplate code compared to the specialized WooCommerce shortcuts.

Using wc_get_product_category() keeps your logic concise and ensures you are interacting with the specific data model WooCommerce uses for rendering front-end elements. If you are migrating complex e-commerce logic or building a multi-vendor marketplace where category structures vary, sticking to the dedicated WooCommerce API functions reduces the risk of breaking changes when WordPress core updates its taxonomy handling.

If you need further assistance integrating this into a larger project or require custom data structures that go beyond standard loops, consider reaching out to specialized development resources like LaravelCompany for guidance on backend architecture and theme customization strategies.

Our network