When you work with WooCommerce PHP snippets, you often need to “get” stuff off your WordPress database in order to make some calculations and return the result on the screen. And if there is something I often google is “How do I get all my store’s product IDs?“.
Thankfully the wc_get_products WooCommerce function gives us the answer. Enjoy ๐
PHP Snippet 1: Get All WooCommerce Product IDs
/**
* @snippet Get All WooCommerce Product IDs
* @how-to Get CustomizeWoo.com FREE
* @author Rodolfo Melogli
* @compatible WooCommerce 7
* @community https://businessbloomer.com/club/
*/
$args = array(
'limit' => -1,
'status' => 'publish',
'return' => 'ids',
);
$products = wc_get_products( $args );
PHP Snippet 2: Get All WooCommerce Product IDs by Product Tag
/**
* @snippet Get WooCommerce Product IDs by Tag
* @how-to Get CustomizeWoo.com FREE
* @author Rodolfo Melogli
* @compatible WooCommerce 7
* @community https://businessbloomer.com/club/
*/
$args = array(
'limit' => -1,
'status' => 'publish',
'return' => 'ids',
'tag' => array( 'tall' ),
);
$products = wc_get_products( $args );
PHP Snippet 3: Get All WooCommerce Product IDs by Product Category
/**
* @snippet Get WooCommerce Product IDs by Category
* @how-to Get CustomizeWoo.com FREE
* @author Rodolfo Melogli
* @compatible WooCommerce 7
* @community https://businessbloomer.com/club/
*/
$args = array(
'limit' => -1,
'status' => 'publish',
'return' => 'ids',
'category' => array( 'books' ),
);
$products = wc_get_products( $args );
Thanks for this, it works well. Is it possible to include a “sort by” dropdown above the list so that a viewer can sort by price or alphabetically.
Hi Steve, thanks so much for your comment! Yes, this is definitely possible, but I’m afraid it’s custom work. If you’d like to get a quote, feel free to contact me here. Thanks a lot for your understanding!
Hi!!!
If I am on Shop page and I want to get the details of all products present on shop when I am using hook.How this can be done? In above examples you have explained how to get each products from query. But if I am using hook ‘ ‘woocommerce_before_shop_loop’ to modify data on page, how can I get all products of page?
Hi Amit! You can use get_posts even inside a frontend snippet