21 December 2021

How to display a list of products by the order status

How to create a list of products a customer has ordered over time based on the status of the orders. You can change the status to compelted, on hold, cancelled etc. as required.

Link to the video:
https://www.youtube.com/watch?v=HhLvuEkcuD8

The function used:

 
function by_products_bought_by_curr_user() {
   
    // GET THE CURRENT USER
    $current_user = wp_get_current_user();
    if ( 0 == $current_user->ID ) return;
   
    // GET THE ORDERS (COMPLETED + PROCESSING)
    $customer_orders = get_posts( array(
        'numberposts' => -1,
        'meta_key'    => '_customer_user',
        'meta_value'  => $current_user->ID,
        'post_type'   => wc_get_order_types(),
        'post_status' => array_keys( wc_get_is_paid_statuses( ) ),
    ) );
   
    // LOOP THROUGH ORDERS AND GET THE PRODUCT IDS
    if ( ! $customer_orders ) return;
    $product_ids = array();
    foreach ( $customer_orders as $customer_order ) {
        $order = wc_get_order( $customer_order->ID );
		$order_status = $order->status;

    // SET THE STATUS TO YOUR PREFERRED STATUS 
		if( $order_status == 'completed' ){
        $items = $order->get_items();
        foreach ( $items as $item ) {
			$product_id = $item->get_product_id();
            $product_ids[] = $product_id;
        }
    }}
    $product_ids = array_unique( $product_ids );
    $product_ids_list = implode( ",", $product_ids );
	return $product_ids_list;
}
BYoung Design
CONTACT
Newsletter Form (#17)

Subscribe to our newsletter

Welcome to our Newsletter Subscription Center. Sign up in the newsletter form below to receive the latest news and updates.


Want to rank higher in search engines?

There are a number of factors that can affect how high your website ranks in search engines such as Google. These factors include the keywords you optimize your site for, your domain's age, keyword density, and the amount of, quality, backlinks to your site. In order to rank your site higher in search engines, you will need to work on gaining the proper backlinks and targeting high traffic keywords.

We can help you rank better.
Back to Top
envelopephonemenuchevron-upcross-circle