Justin
Justin

Reputation: 53

PHP: Get first array in a loop

I have the following code:

$customer_orders = get_posts(array(
    'numberposts' => -1,
    'meta_key' => '_customer_user',
    'meta_value' => get_current_user_id(),
    'post_type' => 'shop_order',
    'post_status' => array_keys(wc_get_order_statuses()),
    )
);

$last_post_date;
$loop = new WP_Query($customer_orders);
foreach ($customer_orders as $orderItem)
{
    $order = wc_get_order($orderItem->ID);
    $last_post_date = $orderItem->post_date;
}

echo $last_post_date;

I want to print the $last_post_date, which is created from an order made by a customer.

So if a customer makes 2 order I will get an array [0] and [1].

But at the moment $last_post_date is not printing the post_date from array[0].

It is always printing the post date from the order that was made first, not last,

Thanks for the help!

Upvotes: 0

Views: 181

Answers (2)

Raunak Gupta
Raunak Gupta

Reputation: 10799

As you have 2 order so the $last_post_date is getting replaced by substituent post_date. So if you want to extract only the first order date then you can add a checking.

Try this code:

foreach ($customer_orders as $key => $orderItem) //<-- added $key
{
    if ($key == 0) //only for first element.
    {
        $last_post_date = $orderItem->post_date;
    }
    $order = wc_get_order($orderItem->ID);
}

echo $last_post_date;

Hope this helps!

Upvotes: 1

Nileshsinh Rathod
Nileshsinh Rathod

Reputation: 968

$customer_orders = get_posts( array(
'numberposts' => -1,
'meta_key'    => '_customer_user',
'meta_value'  => get_current_user_id(),
'post_type'   => wc_get_order_types(),
'post_status' => array_keys( wc_get_order_statuses() ),
) );
print_r($customer_orders);

Try this code the output as below i think this will help you.

Array
(
    [0] => WP_Post Object
        (
            [ID] => 38
            [post_author] => 1
            [post_date] => 2017-01-16 10:00:59
            [post_date_gmt] => 2017-01-16 10:00:59
            [post_content] => 
            [post_title] => Order – January 16, 2017 @ 10:00 AM
            [post_excerpt] => 
            [post_status] => wc-completed
            [comment_status] => open
            [ping_status] => closed
            [post_password] => order_587c99db9ac46
            [post_name] => order-jan-16-2017-1000-am
            [to_ping] => 
            [pinged] => 
            [post_modified] => 2017-01-16 10:03:19
            [post_modified_gmt] => 2017-01-16 10:03:19
            [post_content_filtered] => 
            [post_parent] => 0
            [guid] => http://localhost/wordpress/?post_type=shop_order&p=38
            [menu_order] => 0
            [post_type] => shop_order
            [post_mime_type] => 
            [comment_count] => 2
            [filter] => raw
        )

)

Upvotes: 0

Related Questions