When a WooCommerce customer is logged in, you might want to show the list of purchased products, for example in a custom “My Account” tab.

I decided to code this as a shortcode, so that you can use the snippet anywhere in your WooCommerce templates, as long as the user is logged in and as long as it has processing or completed orders. Enjoy!

WooCommerce: display products bought by user via a shortcode

PHP Snippet: Display All Products Purchased by User – WooCommerce

Once you upload the snippet to your website, use the following shortcode where you need (it will only work when the user is logged in, so for example the My Account page would be ideal):

[my_purchased_products]

/**
 * @snippet       Display All Products Purchased by User via Shortcode - WooCommerce
 * @how-to        Get CustomizeWoo.com FREE
 * @author        Rodolfo Melogli
 * @compatible    WooCommerce 3.6.3
 * @donate $9     https://businessbloomer.com/bloomer-armada/
 */
 
add_shortcode( 'my_purchased_products', 'bbloomer_products_bought_by_curr_user' );
  
function bbloomer_products_bought_by_curr_user() {
  
    // GET CURR USER
    $current_user = wp_get_current_user();
    if ( 0 == $current_user->ID ) return;
  
    // GET USER 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 PRODUCT IDS
    if ( ! $customer_orders ) return;
    $product_ids = array();
    foreach ( $customer_orders as $customer_order ) {
        $order = wc_get_order( $customer_order->ID );
        $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_str = implode( ",", $product_ids );
  
    // PASS PRODUCT IDS TO PRODUCTS SHORTCODE
    return do_shortcode("[products ids='$product_ids_str']");
  
}
Share:

Leave a Reply