questions

Get specific value in a post meta data array (WooCommerce)

Rate this post

I’m looking to just return the value of refundable_amount $7.83 for the query below. Any advice would be greatly appreciated.

SELECT post_id, meta_value
FROM postmeta
WHERE meta_key = 'wc_connect_labels'
AND post_id =1561

returns – >

a:1:{i:0;a:19 {s:8:"label_id";i:3379931;s:8:"tracking";s:22:"9405536205309714712744";s:17:"refundable_amount";d:7.83;s:7:"created";i:1615557045479;s:10:"carrier_id";s:4:"usps";s:12:"service_name";s:20:"USPS - Priority Mail";s:6:"status";s:9:"PURCHASED";s:22:"commercial_invoice_url";N;s:12:"package_name";s:20:"Regional Rate Box A1";s:9:"is_letter";b:0;s:13:}s:11:"product_ids";a:2:{i:0;i:1078;i:1;i:931;}s:15:"receipt_item_id";i:73747484;s:12:"created_date";i:1615557050000;s:11:"expiry_date";i:1631109049000;s:15:"main_receipt_id";i:55385442;s:4:"rate";d:7.83;s:8:"currency";s:3:"USD";s:12:"label_cached";i:1615557053000;}}

 

✔️Solution:

You can use instead the WordPress function get_post_meta() that deserialize array values as follows where you will be able to get easily the “refundable_amount” value like:

$post_id = 1561;

$connect_labels = get_post_meta( $post_id, 'wc_connect_labels', true );

if ( isset($connect_labels['refundable_amount']) ) {
    $refundable_amount = esc_attr( $connect_labels['refundable_amount'] );
}

Or from a WC_Product object using the WC_Data method get_meta() like:

$product = wc_get_product( 1561 ); // If needed

$connect_labels = $product->get_meta('wc_connect_labels');

if ( isset($connect_labels['refundable_amount']) ) {
    $refundable_amount = esc_attr( $connect_labels['refundable_amount'] );
}

Both should work.

Leave a Reply

Your email address will not be published.

Back to top button