Can’t find customers order and product ID

I’m using woo-commerce with the membership and subscription extensions. I’m trying to display the expiration date of the current users subscription for which I need the subscription key to access it.

To find this key I need the product_id and order_id and (because these two values make up the key, “254_119” for example.). But when I try and access the current users order with

Read More
$order = new WC_Order(ID);
print_r($order);

The order data is empty, I tried to access the user_meta in the database as well before realising that it only contains shipping info and such.

Is it possible to access the current users most recent order? I’ve read that I may need to use

get_posts() 

But I’m not sure of the parameters to access the data I require.

This doesn’t seem to work either.

$customer_orders = get_posts($order_count);

Related posts

1 comment

  1. If I understand your question correctly, then approach should be :

    Get most recent order of current User.

    /*Get most recent order of customer*/
    $recent_orders = get_posts( array(
        'numberposts' => 1,
        'meta_key'    => '_customer_user',
        'meta_value'  => get_current_user_id(), //Current user's id
        'post_type'   => wc_get_order_types(),
        'post_status' => array_keys( wc_get_order_statuses() ),
    ) );
    

    Now as we have most recent order, we can get order_id from that order.

    $order_id = $recent_orders[0]->ID; //Order Id
    

    Now to get Products of that order, we can do as following :

    $order = new WC_Order($order_id);
    $cart_item = $order->get_items();//Get Cart Items of that order
    

    Now we have both product_id and order_id so we can make a key :

    foreach($cart_item as $item){
        echo "Product Name : ".$item['name'];
        echo "<br>";
        echo "Product Id : ".$item['product_id'];
        echo "<br>";
        echo "Your Key ".$order_id."_".$item['product_id'];
        echo "<br>";
    }
    

    All Code together :

    <?php 
        /*Get most recent order of customer*/
        $recent_orders = get_posts( array(
            'numberposts' => 1,
            'meta_key'    => '_customer_user',
            'meta_value'  => get_current_user_id(), //Current user's id
            'post_type'   => wc_get_order_types(),
            'post_status' => array_keys( wc_get_order_statuses() ),
        ) );
    
        $order_id = $recent_orders[0]->ID; //Order Id
        $order = new WC_Order($order_id);
    
        $cart_item = $order->get_items();//Get Cart Items of that order
        foreach($cart_item as $item){
            echo "Product Name : ".$item['name'];
            echo "<br>";
            echo "Product Id : ".$item['product_id'];
            echo "<br>";
            echo "Your Key ".$order_id."_".$item['product_id'];
            echo "<br>";
        }
    ?>
    

    Let me know if you have any doubt.

Comments are closed.