Get specific value from a post meta array variable value in WooCommerce

Viewed 133

I'm trying to get the value of a "key" inside the wp_postmeta database of wordpress.

I have this set up in the database.

postId: xxxx

metaKey: _sco_post_data

metaValue : a:5:{s:15:"billing_country";s:2:"SE";s:16:"billing_postcode";s:5:"99999";s:14:"order_comments";s:14:"fdsfdafasdfasf";s:18:"dtwc_delivery_date";s:10:"2020-10-06";s:18:"dtwc_delivery_time";s:5:"19:30";}

Now, in my functions.php I wanted to get the specific value only for 'dtwc_delivery_date' and 'dtwc_delivery_time'. I tried but the only I am able to get this is by enclosing them in a foreach loop.

function my_function( $order_id ) {
$order = wc_get_order( $order_id );
$meta = $order->get_meta('_sco_post_data'); //this returns an array

foreach ( $meta as $item ) {
    echo '<p><strong>'.__('Test Value').':</strong> ' .  $item. '</p>'; 
}

The result of the code above is as follows: Test Value: SE

Test Value: 99999

Test Value: fdsfdafasdfasf

Test Value: 2020-10-06

Test Value: 19:30

What would I've wanted to be able to call the value like:

$meta['dtwc_delivery_date'] but this doesn't return anything. It's empty.

1 Answers

Normally $meta['dtwc_delivery_date'] should work… Now you can use print_r() function on your array to see how is built and a foreach loop with indexes (Keys) to be able to check the keys and to see if it will work as you are expecting like:

function my_function( $order_id ) {
    $order  = wc_get_order( $order_id ); // Order object
    $values = $order->get_meta('_sco_post_data'); // get meta value (array)

    // Raw formatted output from the array to check how comes the data
    echo '<pre>'. print_r( $obj, true ) . '</pre>';

    // The loop
    foreach ( $values as $key => $value ) {
        // displaying array raw formatted output (and checking if you can get a value from its key
        echo '<p>Key: '. $key . ' | Value: '. $value . ' | Value from the key: '. $values[$key] . '<p>';
    }
}

This should help you.

Related