后端 WooCommerce 3+ WC_Order

WooCommerce 3+ WC_Order in backend

我在 Woocommerce 3.X 中遇到一个功能问题。我(想我)理解这是因为 WC_Order 不能再直接访问,但我不确定如何在函数中修复它(我没有写)。

//Admin JS
    add_action('admin_enqueue_scripts', 'admin_hooks');
    function admin_hooks( $hook ) {

        global $woocommerce, $post;
        $order = new WC_Order($post->ID);
        //to escape # from order id
        $order_id = trim(str_replace('#', '', $order->get_order_number()));
        $user_id = $order->user_id;
        $user_info = get_userdata($user_id);


        wp_enqueue_script( 'admin-hooks', get_template_directory_uri(). '/js/admin.hook.js' );
        wp_localize_script( 'admin-hooks', 'myTest', $user_info->roles );
    }

我尝试将 $order = new WC_Order($post->ID); 更改为 $order = new wc_get_order( $order_id ); 但没有成功,这有点道理。我可以看到我正在尝试获取 post id 而不是订单 id,只是不确定如何获取。如您所见,我只是在研究代码,所以放轻松。我确实看到了 但无法弄清楚如何使用我的代码来实现,欢迎任何输入。

为了快速提供有关该功能功能的反馈,它在管理订单页面上显示了登录用户角色。

您只能在后端的 "post edit pages" 中获取 post ID,因此对于订单,它将是 "order edit pages"(而不是 "Orders list pages")。

在您挂钩的函数中 admin_enqueue_scripts 您只需要定位订单编辑页面。

您不需要获取 WC_Order 对象,对于订单页面,订单 ID 是 Post ID。

订单中的用户 ID 是客户 ID(通常是 'customer' 用户角色)。
此外,对于信息,$user_info->roles; 是一个数组!

所以正确的代码是:

add_action('admin_enqueue_scripts', 'admin_hooks');
function admin_hooks( $hook ) {

    // Targeting only post edit pages
    if ( 'post.php' != $hook && ! isset($_GET['post']) && ! $_GET['action'] != 'edit' )
        return;

    // Get the post ID
    $post_id = $_GET['post']; // The post_id

    // Get the WP_Post object
    $post = get_post($post_id);

    // Targeting only Orders
    if( $post->post_type != 'shop_order' )
        return;

    // Get the customer ID (or user ID for customer user role)
    $customer_id      = get_post_meta( $post_id, '_customer_user', true ); 
    $user_info        = get_userdata($customer_id);

    $user_roles_array = $user_info->roles; // ==> This is an array !!!

    wp_enqueue_script( 'admin-hooks', get_template_directory_uri(). '/js/admin.hook.js' );
    wp_localize_script( 'admin-hooks', 'myTest', $user_roles_array );
}

代码进入您的活动子主题(或主题)的 function.php 文件或任何插件文件。

我无法测试此代码,因为它涉及其他外部文件。但它应该有效。