Search code examples
phpwordpresswoocommercehook-woocommerceorders

Order save hook user permissions check for WooCommerce HPOS


Before HPOS the order save hook can be checked this way:

<?php
use Automattic\WooCommerce\Utilities\OrderUtil;

add_action('save_post', 'my_save_wc_order_other_fields', 20, 1);
function my_save_wc_order_other_fields($post_id)
{
    // this check is HPOS aware already
    if (!OrderUtil::is_order($post_id, wc_get_order_types())) {
        return;
    }

    // We need to verify this with the proper authorization (security stuff).

    // Check the user's permissions.
    // TODO: this code is not HPOS aware yet?!
    if (!current_user_can('edit_shop_order', $post_id)) {
        return $post_id;
    }
}

How the current_user_can('edit_shop_order', $post_id) part should be replaced for the HPOS support?


Solution

  • The save order hook since WooCommerce 3 for Admin create/edit order page has always been woocommerce_process_shop_order_meta and still works with High-Performance Order Storage (HPOS).

    Checking for user capability is not really needed anymore with this hook, but if you want it, you can use something like:

    add_action( 'woocommerce_process_shop_order_meta', 'update_shop_order_custom_data', 40 );
    function update_shop_order_custom_data( $order_id ) {
        global $current_user;
        
        if ( ! in_array( 'edit_shop_order', $current_user->allcaps ) ) {
            return;
        }
    
        $order = wc_get_order($order_id); // Get WC_Order object instance
        
        // Update WC_Order custom meta data
        if ( isset($_POST['meta_key']) ) {
            $order->update_meta_data( 'meta_key', esc_attr($_POST['meta_key']) );
            $order->save();
        }
    }
    

    Related: Add a custom Metabox to WooCommerce admin orders with HPOS enabled