mrk1357
mrk1357

Reputation: 33

Get all Woocommerce product IDs in an array

How do I get IDs of all products in one array?

The output should be a simple array containing some numbers, nothing more.

I have been advised against using query_posts(), so I would prefer a solution not using this function.

Upvotes: 2

Views: 5666

Answers (1)

LoicTheAztec
LoicTheAztec

Reputation: 253814

There is multiple ways to get all product ids in an array:

1) Using Woocommerce WC_Product_Query:

$ids = wc_get_products( array( 'return' => 'ids', 'limit' => -1 ) );

2) Using Wordpress WP_Query (including product variations IDs),

$ids = get_posts( array(
  'posts_per_page' => -1,
  'post_type' => array('product','product_variation'),
  'fields' => 'ids',
) );

3) Using a WPDB (a SQL query) (including product variation IDS):

global $wpdb;
$ids = $wpdb->get_col( "SELECT ID FROM {$wpdb->prefix}posts WHERE post_type IN ('product','product_variation')");

In the 2 last ways you can remove 'product_variation' post type, if you don't want it.

Upvotes: 11

Related Questions