php - 在 Woocommerce 中添加自定义字段作为订单备注

标签 php wordpress woocommerce orders user-roles

我正在尝试添加自定义字段jckwds_date作为订单备注。我一生都无法弄清楚为什么这段代码在 functions.php 中不起作用?

代码还只允许在特定角色类型中添加注释。

function wdm_my_custom_notes_on_single_order_page($order){

    $user = wp_get_current_user();
    $allowed_roles = array('eu_no_vat', 'super_wholesale_customer', 'wholesale_customer');

    if( array_intersect($allowed_roles, $user->roles ) )  {

        $value = get_post_meta( $product->get_id(), 'jckwds_date', true );

        echo $value;

        $order->add_order_note( $value, $is_customer_note = 1 );

    }
}

基本上我需要THIS :

THIS

待添加HERE :

HERE

最佳答案

更新:

以下代码将从订单自定义字段“jckwds_date”(或结帐发布字段值“jckwds_date”)添加订单注释,该注释将显示在后端中定义的用户角色:

add_action( 'woocommerce_checkout_update_order_meta', 'product_custom_field_to_custom_order_notes', 100, 2 );
function product_custom_field_to_custom_order_notes( $order_id, $data ){
    // HERE define allowed user roles
    $allowed_roles = array('administrator', 'super_wholesale_customer', 'wholesale_customer');

    $user_id = get_post_meta( '_customer_user', 'jckwds_date', true );
    $user = new WP_User( $user_id );

    // Exit if no matched user roles
    if( ! array_intersect( $allowed_roles, $user->roles ) ) return;

    // Get the date custom field (or checkout field)
    if( get_post_meta( $order_id, 'jckwds_date', true ) ){
        $note = get_post_meta( $order_id, 'jckwds_date', true );
    } elseif( isset( $_POST['jckwds_date'] ) ){
        $note = sanitize_text_field( $_POST['jckwds_date'] );
    }

    // The order note
    if( isset($note) && ! empty($note) ){
        $order = wc_get_order( $order_id ); // The WC_Order Object
        $order->add_order_note( $note );  // Add the note
        $order->save(); // Save the order
    }
}

代码位于事件子主题(或事件主题)的 function.php 文件中。它应该可以工作。

关于php - 在 Woocommerce 中添加自定义字段作为订单备注,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51494501/

相关文章:

php - 比较日期是否已过

php - 使用 mcrypt 或 GnuPG 存储信用卡详细信息

php - 将 Wordpress 复制到 Staging 丢失 wp_options

php - 在 Woocommerce 结帐页面中添加城市下拉列表

php - 将文本字符串附加到 WooCommerce 产品标题

php - 确定 PHP 中是否存在数组键有什么更快更好的方法?

php - 拉维尔 : Join two tables get the info from table one and get the first related image from table two

javascript - WordPress的。在光标到达下一个选项卡之前,下拉菜单消失。仅在登录时

wordpress - 更改站点地图 Yoast 的名称

php - 根据项目自定义字段最高值在购物车和结帐页面上添加通知