0

If a checkbox is checked, it saves a value of 1 for a 'my_checkbox' custom order field in WooCommerce. I'm editing the order admin table and I need to be able to echo a particular icon url if the value of 'my_checkbox' equals 1. I just don't know how to check if the value is equal to one so I can echo the url. Any ideas?

To make troubleshooting easier, here's the code:

/**
* Add checkbox field to the checkout
**/
add_action('woocommerce_after_checkout_billing_form', 'match_previous_order_checkbox');

function match_previous_order_checkbox( $checkout ) {
echo '<div id="match_the_order">';
woocommerce_form_field( 'my_checkbox', array(
     'type'     => 'checkbox',
     'class'    => array('form-row notes'),
     'label'    => __( 'This is a previous order' , 'woothemes'),
     'required' => false,
    ), 
    $checkout->get_value( 'my_checkbox' ));
    echo '</div>';
}
/**
* Update the order meta with field value
**/
add_action('woocommerce_checkout_update_order_meta', 'match_order_checkout_field_update_order_meta');

function match_order_checkout_field_update_order_meta( $order_id ) {
    if ($_POST['my_checkbox']) {
    update_post_meta( $order_id, 'My_Checkbox', esc_attr($_POST['my_checkbox']));
    }
}
global $order;
$match_order_meta = get_post_meta( $order_id , 'My_Checkbox' );

$match_order_meta = get_post_meta( $order->ID , 'My_Checkbox' ); doesn't work either. Also whether or not I include global $order; doesn't seem to matter.

1 Answer 1

1

WooCommerce orders are posts and behave the same as any WordPress post. So you can use the same WordPress functions to update or read the post meta data.

<?php $meta_values = get_post_meta($post_id, $key, $single); ?>

For your example I'd suggest:

$match_order_meta = get_post_meta( $order->ID, 'My_Checkbox', TRUE);

The 'TRUE' flag tells WordPress to return the value as a string. Without the TRUE flag you'll get an array. Again take a look at the docs below.

You might also:

echo '<!-- $order->ID -->';

To make sure you have the correct ID.

Here are the docs get_post_meta().

4
  • I can't seem to get this to work. I'm using: <?php $meta_values = get_post_meta( $order->ID , 'my_checkbox' ); ?> but no values are returned, even though orders exist. Commented Feb 4, 2013 at 20:46
  • Does your $order-ID equal the post ID?
    – Steve
    Commented Feb 4, 2013 at 20:58
  • I put my code in the question above. The $order id should be the post id. Here's the code from WooCommerce: global $post, $woocommerce; $order = new WC_Order( $post->ID ); Commented Feb 4, 2013 at 21:52
  • Thanks for your help. I ended up getting it by just using $post->ID and left $order->ID completely out of it. Commented Feb 5, 2013 at 5:42

Your Answer

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

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