2

I have setup a custom field in the Admin Orders section of my Woocommerce site

add_action('woocommerce_admin_order_data_after_order_details', function($order){
    $pdf_url = get_post_meta($order->get_id(), '_order_pdf_link', true);
   echo '<p></p><br>';
    echo '
<p style="margin-top:25px;"><strong>Report File URL:</strong></p>
<input type="text" id="_order_pdf_link" name="_order_pdf_link" style="width:100%;" value="' . esc_attr($pdf_url) . '" placeholder="Paste file URL (PDF, image, etc.) here" />';

});

After this added code to save the value on order save/update

add_action('woocommerce_process_shop_order_meta', function($order_id){
    if (isset($_POST['_order_pdf_link'])) {
        update_post_meta($order_id, '_order_pdf_link', esc_url_raw($_POST['_order_pdf_link']));
    }
});

Even modified the rest api get response to get the value as below:

function prefix_wc_rest_prepare_order_object( $response, $object, $request ) {
    // Get the value
    $reference_meta_field = ( $value = get_post_meta($object->get_id(), '_order_pdf_link', true) ) ? $value : '';
 
    $response->data['_order_pdf_link'] = $reference_meta_field;
 
    return $response;
}
add_filter( 'woocommerce_rest_prepare_shop_order_object', 'prefix_wc_rest_prepare_order_object', 10, 3 );

All of this works perfectly. Challenge is when I try to set that value of this field by calling PUT on Order API using the metadata section - the response and subsequent get shows the metadata field but it is not showing on my custom field. Also even though the metadata shows this - the attribute I built using the filter above does not but it does show when created manually. It almost makes me wonder if the PUT api call is setting it to order metadata and not the post metadata.

1 Answer 1

0

WooCommerce REST API PUT doesn’t save to postmeta, it saves to order meta. That’s why your custom field doesn’t see it. Instead of get_post_meta(), use WooCommerce’s $order->get_meta() / $order->update_meta_data() API.

// Admin field
$pdf_url = $order->get_meta('_order_pdf_link');
// REST response filter
$reference_meta_field = $object->get_meta('_order_pdf_link');
$response->data['_order_pdf_link'] = $reference_meta_field;
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.