Woocommerce how to get order status?

If you are writing plugin (like me) under Woocommerce 2.0 to get a list of order of particular order status, you will find that it does not exists in wp_posts and wp_postmeta.

Simply put:

  1. All order status strings (e.g. completed, failed, on-hold etc) are stored in wp_terms
  2. Using wp_terms.term_id, you can find your order ID in wp_term_relationships.  In this table, order ID is called "object_id"
  3. You can now do a search on wp_posts using wp_term_relationships.object_id (wp_term_relationships.object_id is now post_id)
You don't need to write SQL to do the above 3 steps, Wordpress has already provided similar functions to do this.  They are get_term_by and get_objects_in_term.  Sample code below:

$status = get_term_by( 'slug', sanitize_title( $_POST['order_status'] ), 'shop_order_status' );
$s = get_objects_in_term($status->term_id, 'shop_order_status');

It will return order IDs in array, like:

0 => string '1457' (length=4)
1 => string '1459' (length=4)
2 => string '2067' (length=4)
3 => string '2071' (length=4)

Hope it helps someone.


Popular posts from this blog

TCPDF How to show/display Chinese Character?

Using wget bypass htaccess username password 401 authorization

Wordpress Load balancing: 2 web servers 1 MySQL without any Cloud services