如何在 Woocommerce 中更新 billing_email(如果为空)

How to update billing_email in Woocommerce (if empty)

结帐页面上的电子邮件地址不是必需的。

如果客户未提供电子邮件,我们希望将 billing_email 更新为我们的自定义电子邮件。

这是我的代码:

add_action('woocommerce_thankyou', 'set_email_for_guest');
function set_email_for_guest( $order_id ) {
    $email = get_post_meta( $order_id, 'billing_email', true );
    if(empty($email)){
            update_post_meta( $order_id, '_billing_email', 'example@example.com' );
    }
}

您的元键有误:

add_action( 'woocommerce_thankyou', 'set_email_for_guest' );
function set_email_for_guest( $order_id ) {
    $email = get_post_meta( $order_id, '_billing_email', true ); // '_billing_email' instead 'billing_email'

    if( empty( $email ) ) {
        update_post_meta( $order_id, '_billing_email', 'example@example.com' );
    }
}

如果用户在结帐时未提供帐单电子邮件,您想将 billing_email 更新为自定义电子邮件。

因此,为结帐页面上的电子邮件字段提供默认值可能是解决问题的方法。如果已登录,此默认值可以是客户电子邮件,或者在您的示例中是硬编码值。这样您将始终在此字段中有一个值。

add_filter( 'woocommerce_checkout_fields', 'set_billing_email_default_value' );
 
function set_billing_email_default_value($fields) {
    $fields['billing']['billing_email']['default'] = 'example@example.com';
    return $fields;
}

加法:

如果你想让它只读,这样用户就不能编辑默认值,你可以在字段自定义属性中设置这个。

$fields['billing']['billing_email']['custom_attributes'] = array('readonly'=>'readonly');

我认为您应该使用的钩子是而不是 woocommerce_thankyou。相反,您应该从以下钩子中选择一个,它们在 WordPress 5.6.1 和 WooCommerce 5.0.0 中都对我有用(在撰写本文时都是最新版本):

请注意,这些挂钩将 $data 作为第二个参数传递,它是 POST-ed/submitted(已处理)表单数据的数组。但是,第一个参数分别是 WC_Order 实例和订单 ID。

选项 1:使用 woocommerce_checkout_create_order

add_action( 'woocommerce_checkout_create_order', 'set_email_for_guest', 10, 2 );
function set_email_for_guest( $order, $data ) { // first param is a WC_Order instance
    if ( empty( $data['billing_email'] ) ) {
        $order->update_meta_data( '_billing_email', 'foo@example.com' );
    }
}

选项 2:使用 woocommerce_checkout_update_order_meta

add_action( 'woocommerce_checkout_update_order_meta', 'set_email_for_guest', 10, 2 );
function set_email_for_guest( $order_id, $data ) { // first param is an order/post ID
    if ( empty( $data['billing_email'] ) ) {
        update_post_meta( $order_id, '_billing_email', 'foo@example.com' );
    }
}

所以只要选择你喜欢的钩子,但上面的第一个钩子会先运行。