0

I am trying to get a specific meta value from all of a customer's orders and simply echo them to the Downloads page within My Account. This is what I have so far, but unable to get $skey to retrieve and display the assigned values that are set from the backend. Basic idea is to go to a customer's order, define what we need for said order in the s_key custom field and just have that populate for customers just after their download links purchased.

Any help on this would be awesome! Certified php beginner so its possible I am doing something not quite right.

function return_s_key_field() {
$args = array(
'customer_id' => $user_id);
$orders = wc_get_orders($args);
$skey = get_post_meta( $orders, 's_key', true );

echo ('<div id="request_title"></div>');

if ( empty($skey) == 'true' || $skey != 'N/A' ){
    echo ('<div id="key_container"><div id="key_label"><p>Arbitrary text:</p></div><div id="steam_key"><p>' . $skey . '</p></div></div>'); 
}
else { 
    echo ('<div id="key_container"><div id="key_label"><p>Arbitrary text:</p></div><div id="steam_key"><p>N/A</p></div></div>');
}
}
add_action( 'woocommerce_after_available_downloads', 'return_s_key_field' );
0

Some basic issues with code. Since this hook do not have any data supplied to function, you need to get current user logged in.

Secondly, as already mentioned by @antti, get_post_meta accepts first parameter as post id (in this case order id), single value.

function return_s_key_field() {

$orders = wc_get_orders(array(
    'customer_id' => get_current_user_id(),
    'return' => 'ids',
))

$meta_data = array();

foreach ($orders as $order_id) {
  $meta_data[$order_id] = get_post_meta($order_id, 's_key', true);  
}

// var_dump($meta_data);

}
add_action( 'woocommerce_after_available_downloads', 'return_s_key_field' );

Try un-commenting var_dump and then use that data however it is required.

  • Works like a charm! Thank you soo much @AntiiKoshkinen thank you also – Anvilhouse Dec 17 '19 at 19:44
0

The problem with your code is that you're passing an array of orders, which wc_get_orders() to my knowledge returs but check WooC documentation, to get_post_meta(), which expects the first parameter to be an integer post ID.

So modify your orders query to return only IDs, then loop that array through and on each iteration execute the get_post_meta() for that particular ID. Push the found meta data to a helper array variable and then use the data to do something after the loop has finished.

$order_ids = array(); // array of WooC order IDs
$meta_data = array();

foreach ($order_ids as $order_id) {
  $meta_data[$order_id] = get_post_meta($order_id, 's_key', true);  
}

if ( $meta_data ) {
  // do something
}

https://developer.wordpress.org/reference/functions/get_post_meta/

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.