我如何在WooCommerce Checkout中保留用户偏好-发送到不同的地址



在WooCommerce购物车中,您可以将默认值设置为发送到账单地址。然后,用户可以选中一个复选框来启用不同的送货地址。对于回头客来说,你不得不再次打勾是件麻烦事。我想记住登录用户的复选框的状态,这样不仅显示地址信息,而且复选框的状态与上次订单的状态相同。

发布了一些代码片段,您可以在其中添加额外的字段到shipping或billing,并让WooCommerce处理存储。其他示例显示了在post中存储数据的自定义字段。这在当前订单上保持,但在下一个订单上不可用。

所以我用下面的内容回答了我自己的问题。首先在子主题的functions.php中执行一个操作,将复选框的状态保存在用户元数据中:

/**
 * Update the user meta with checkbox setting
*/
add_action( 'woocommerce_checkout_update_order_meta', 'my_custom_checkout_field_update_order_meta' );
function my_custom_checkout_field_update_order_meta( $order_id ) {
   $order = new WC_Order( $order_id );
   update_user_meta( $order->user_id , 'shipping_different',$_POST['ship_to_different_address'])   ;
}

然后添加一个操作来检索存储的复选框值并更新复选框:

/*
 * Get the user meta to set the checkbox if needed
 */
add_action( 'woocommerce_after_checkout_billing_form', 'my_checkout_fields', 10,1 );
function my_checkout_fields( $checkout ) {
    $user_id = get_current_user_id();
    if ($user_id !=0 ) {
        if (get_user_meta($user_id, 'shipping_different', true ) == 1)
        add_filter( 'woocommerce_ship_to_different_address_checked',     '__return_true' );
    }
}

评论?改进吗?

最新更新