WooCommerce Product Query Methods: Complete Implementation from Categories to Product Lists

Nov 23, 2025 · Programming · 9 views · 7.8

Keywords: WooCommerce | Product Query | WordPress Development | WP_Query | Product Categories

Abstract: This article provides a comprehensive exploration of retrieving product categories and product lists under specific categories in WordPress WooCommerce. By analyzing three different implementation approaches, it focuses on the standard practice using WP_Query while comparing the modern wc_get_products API and the simplified get_posts method. The article includes detailed code examples, parameter explanations, and best practice recommendations to help developers build stable and reliable product display functionality.

Basic Implementation of Product Category Retrieval

In WooCommerce development, retrieving product categories is a fundamental step in building product navigation systems. Using WordPress's get_categories() function with appropriate parameter configurations enables efficient retrieval of product category information.

The following code demonstrates how to retrieve all top-level product categories and their subcategories:

<?php
$taxonomy     = 'product_cat';
$orderby      = 'name';  
$show_count   = 0;
$pad_counts   = 0;
$hierarchical = 0;
$title        = '';
$empty        = 0;

$args = array(
  'taxonomy'     => $taxonomy,
  'orderby'      => $orderby,
  'show_count'   => $show_count,
  'pad_counts'   => $pad_counts,
  'hierarchical' => $hierarchical,
  'title_li'     => $title,
  'hide_empty'   => $empty
);

$all_categories = get_categories($args);

foreach ($all_categories as $cat) {
    if($cat->category_parent == 0) {
        $category_id = $cat->term_id;
        
        echo '<br /><a href="'. get_term_link($cat->slug, 'product_cat') .'">'. $cat->name .'</a>';
        
        $args2 = array(
          'taxonomy'     => $taxonomy,
          'child_of'     => 0,
          'parent'       => $category_id,
          'orderby'      => $orderby,
          'show_count'   => $show_count,
          'pad_counts'   => $pad_counts,
          'hierarchical' => $hierarchical,
          'title_li'     => $title,
          'hide_empty'   => $empty
        );
        
        $sub_cats = get_categories($args2);
        if($sub_cats) {
            foreach($sub_cats as $sub_category) {
                echo $sub_category->name;
            }
        }
    }
}
?>

This implementation first defines category query parameters, then processes each top-level category through a loop, and further queries its subcategories. Key parameters include taxonomy specifying product categories, hide_empty controlling whether to display empty categories, and hierarchical determining whether to maintain hierarchical structure.

Product Query Solution Based on WP_Query

Retrieving product lists under specific categories is a core functionality of e-commerce websites. Using WordPress's WP_Query class is the most direct and compatible approach.

The following code demonstrates how to retrieve products under the "hoodies" category:

<?php  
$args = array(
    'post_type'      => 'product',
    'posts_per_page' => 10,
    'product_cat'    => 'hoodies'
);

$loop = new WP_Query($args);

while ($loop->have_posts()) : $loop->the_post();
    global $product;
    echo '<br /><a href="'.get_permalink().'">' . woocommerce_get_product_thumbnail().' '.get_the_title().'</a>';
endwhile;

wp_reset_query();
?>

Key aspects of this implementation include: setting post_type to product to limit query scope, specifying the target category through the product_cat parameter, and controlling the number of returns with posts_per_page. Within the loop, product information is accessed through the global $product object and WooCommerce-specific functions, followed by wp_reset_query() to restore the original query state.

Modern API Approach: wc_get_products

WooCommerce officially recommends using the wc_get_products() function for product queries, providing better forward compatibility.

<?php
$args = array(
    'category' => array('hoodies'),
    'orderby'  => 'name',
);
$products = wc_get_products($args);
?>

This method directly returns an array of WC_Product objects, avoiding compatibility issues caused by database structure changes. Note that the category parameter accepts an array of category slugs rather than IDs.

Simplified Approach: get_posts Function

For simple product query requirements, WordPress's get_posts() function can be used:

<?php
$args = array(
    'post_type' => 'product', 
    'category' => 34, 
    'posts_per_page' => -1
);
$products = get_posts($args);
?>

This approach offers concise code but has relatively limited functionality and potential compatibility risks.

Implementation Details and Best Practices

In actual development, several key factors must be considered. Usage of category identifiers: WP_Query accepts category slugs as product_cat parameter values, while category IDs require complex configuration through tax_query.

Pagination handling: Implement pagination functionality through posts_per_page and paged parameters to avoid performance issues caused by loading large numbers of products at once.

Error handling: Always check if query results are empty and appropriately handle exceptional cases. In theme development, ensure queries are executed at appropriate hook positions to avoid conflicts with WordPress main queries.

Performance optimization: For frequently accessed product lists, consider using WordPress caching mechanisms or WooCommerce-specific caching plugins. Avoid executing additional database queries within loops and properly use the pre_get_posts filter to optimize query performance.

Copyright Notice: All rights in this article are reserved by the operators of DevGex. Reasonable sharing and citation are welcome; any reproduction, excerpting, or re-publication without prior permission is prohibited.