Search code examples
mysqldatabasewordpresswoocommercecustom-post-type

Difference between wp_postmeta and wp_woocommerce_order_itemmeta tables


Seems like both tables are storing metadata of orders in woocommerce. But how to know what data to store to where?

I'm currently using update_post_meta function such as,

update_post_meta( $order_id, 'newcheckboxfield', esc_attr($_POST['newcheckboxfield']) 

to add a custom field (newcheckboxfield) at the checkout for each order. But I prefer if the meta data goes to wp_woocommerce_order_itemmeta table as that seems to be storing relevant data for each order, am I right?


Solution

  • The table wp_woocommerce_order_itemmeta is just for all WooCommerce order items meta data (but not for order meta data).

    The table wp_postmeta handle meta data for all post types like default Wordpress blog post, default Wordpress page, default Wordpress image attachment and all other custom post types.

    Some WooCommerce default custom post types are product, product_variation, shop_coupon, shop_order, shop_order_refund


    To better understand WooCommerce orders:

    • Mostly all checkout fields are stored as order meta data (in wp_postmeta table)
    • Cart item data is stored as order item meta data (in wp_woocommerce_order_itemmeta table)

    WooCommerce Order and Order Item custom fields after checkout

    1) Order meta data

    To add a custom field tas order meta data, you will use the following hooks:

    • woocommerce_checkout_create_order action hook with 2 arguments: $order, $data (see this examples on Stack OverFlow)
    • woocommerce_checkout_update_order_meta action hook with 2 arguments: $order_id, $data (see this examples on Stack OverFlow)

    2) Order item meta data

    To add a custom field as order item meta data, you will use the following hook: