Get the product list of a given Category ID

I suspect the main problem is that you should be using the WP_Query object rather than get_posts(). The later by default only returns items with a post_type of post not products,

So given a category with ID 26, the following code would return it’s products (WooCommerce 3+):

    $args = array(
    'post_type'             => 'product',
    'post_status'           => 'publish',
    'ignore_sticky_posts'   => 1,
    'posts_per_page'        => '12',
    'tax_query'             => array(
        array(
            'taxonomy'      => 'product_cat',
            'field' => 'term_id', //This is optional, as it defaults to 'term_id'
            'terms'         => 26,
            'operator'      => 'IN' // Possible values are 'IN', 'NOT IN', 'AND'.
        ),
        array(
            'taxonomy'      => 'product_visibility',
            'field'         => 'slug',
            'terms'         => 'exclude-from-catalog', // Possibly 'exclude-from-search' too
            'operator'      => 'NOT IN'
        )
    )
);
$products = new WP_Query($args);
var_dump($products);

In earlier versions of WooCommerce the visibility was stored as a meta field, so the code would be:

    $args = array(
    'post_type'             => 'product',
    'post_status'           => 'publish',
    'ignore_sticky_posts'   => 1,
    'posts_per_page'        => '12',
    'meta_query'            => array(
        array(
            'key'           => '_visibility',
            'value'         => array('catalog', 'visible'),
            'compare'       => 'IN'
        )
    ),
    'tax_query'             => array(
        array(
            'taxonomy'      => 'product_cat',
            'field' => 'term_id', //This is optional, as it defaults to 'term_id'
            'terms'         => 26,
            'operator'      => 'IN' // Possible values are 'IN', 'NOT IN', 'AND'.
        )
    )
);
$products = new WP_Query($args);
var_dump($products);

Here we are only returning visible products, 12 per page.

Have a look through http://codex.wordpress.org/Class_Reference/WP_Query#Taxonomy_Parameters for more details about how the category targeting works – it’s often more useful to retrieve it by slug than by ID!

Leave a Comment