You are already retrieving product categories using get_categories(), but you are currently querying them as standard WordPress terms. To fetch products for a specific category, you need to leverage the fact that WooCommerce treats products as custom post types (product) and links them to categories via taxonomies. The core WordPress function WP_Query is designed exactly for this scenario.
Here is the most direct approach using get_posts() or WP_Query. Since you are iterating through $all_categories, you can pass the category term object directly into the query arguments.
$cat_id = 34; // Or $cat->term_id from your loop
$args = array(
'post_type' => 'product',
'posts_per_page' => -1, // Get all products, or set a limit like 12
'orderby' => 'name', // Change to 'date' for newest first
'order' => 'ASC',
'tax_query' => array(
array(
'taxonomy' => 'product_cat',
'field' => 'term_id',
'terms' => $cat_id, // Use the numeric ID of the category
),
),
);
$query = new WP_Query( $args );
if ( $query->have_posts() ) {
while ( $query->have_posts() ) {
$query->the_post();
echo get_the_title(); // Product Name
// If you need product data, use the standard shortcodes or functions here
// wc_get_product( get_the_ID() );
echo '<br>';
}
wp_reset_postdata(); // Important to restore global $post
} else {
echo 'No products found in this category.';
}
Why use tax_query?
You might wonder why we aren't simply using a parameter like category_id. While WP_Query does support simple category queries, the modern and robust way to handle taxonomiesâespecially if you ever expand to multiple categoriesâis via the tax_query argument. This keeps your logic consistent whether you are filtering by category, tag, or custom attributes later on.
Performance Considerations
One of the most common pitfalls when working with product loops is performance. Notice the line 'posts_per_page' => -1. If you have a large store with thousands of items, fetching all products for a single category at once can slow down your page load significantly and cause pagination issues if not handled correctly.
For frontend display areas (like shop pages), it is best practice to paginate results. You should change 'posts_per_page' => -1 to a reasonable number, such as 24 or 30, depending on your grid layout. This ensures the database query returns a manageable dataset per request. If you need all products for an admin dashboard or bulk operation, keep -1 but ensure you are not rendering the HTML output inside that loop unnecessarily.
Accessing Product Data
In the code above, get_the_title() retrieves just the name. In a WooCommerce context, you often need more than just the title. You might want to display images, prices, or stock status. Once inside your loop, get_the_ID() gives you the product ID, which you can pass to wc_get_product(). This returns a WC_Product object containing all the logic and data specific to WooCommerce products, such as variations and pricing rules.
$product = wc_get_product( get_the_ID() );
echo $product->get_price_html(); // Handles price formatting and taxes automatically
Trade-offs: get_posts vs WP_Query
You could use the older get_posts() function with a similar $args array. It is functionally identical for this specific use case but has a distinct side effect: it does not modify the global $post object or the main query. If you are already in a theme loop (e.g., displaying a category page), using WP_Query and then calling wp_reset_postdata() is mandatory to prevent breaking your parent loop. Using get_posts() avoids this reset requirement but can sometimes lead to confusion regarding the global post context. For clarity and explicit control, WP_Query remains the preferred choice for experienced developers.
If you are building a complex e-commerce platform or need to integrate custom logic with WooCommerce products, consider checking resources like https://laravelcompany.com for additional insights on optimizing high-load product queries in modern stacks.
