【发布时间】:2021-02-26 17:02:44
【问题描述】:
我正在尝试添加一个输入字段,允许客户(客人)在“添加到购物车”之前在产品页面上输入他们的邮政编码,然后在购物篮和结帐中设置/预填充邮政编码,而无需输入他们的详细信息或登录/创建帐户。
我看到一些资源说购物篮页面上的运费计算器预填充很复杂,但我不熟悉运费计算器的工作原理。这是真的吗?
基于Add a product note field in single product pages in Woocommerce答案代码,我已经成功地使用以下代码将邮政编码从产品页面传递到结帐页面,该代码允许客人将他们的邮政编码添加到产品页面,并且结帐正确显示正确显示运费的客人邮政编码:
// Add a custom product note after add to cart button in single product pages
add_action('woocommerce_after_add_to_cart_button', 'custom_field_delivery_postcode', 10 );
function custom_field_delivery_postcode() {
woocommerce_form_field('postcode_note', array(
'type' => 'text',
'class' => array( 'my-field-class form-row-wide') ,
'label' => __('Postcode') ,
'placeholder' => __('Enter your service postcode...') ,
'required' => true,
) , '');
}
// Add customer note to cart item data
add_filter( 'woocommerce_add_cart_item_data', 'add_delivery_postcode_to_cart_item_data', 20, 2 );
function add_delivery_postcode_to_cart_item_data( $cart_item_data, $product_id ){
if( isset($_POST['postcode_note']) && ! empty($_POST['postcode_note']) ){
$postcode_note = sanitize_textarea_field( $_POST['postcode_note'] );
$cart_item_data['postcode_note'] = $postcode_note;
}
return $cart_item_data;
}
// If user not logged in, set the guest postcode, otherwise whow saved customer postcode
add_action('woocommerce_after_checkout_form','sab_guest_checkout_postcode');
function sab_guest_checkout_postcode(){
$isLoggedIn = is_user_logged_in();
if(false == $isLoggedIn){
?>
<script type="text/javascript">
jQuery(function($){
$('#billing_postcode').val('<?php
foreach( WC()->cart->get_cart() as $cart_item ){
if( isset($cart_item['postcode_note']) )
echo $cart_item['postcode_note'];
} ?>'); //enter postcode here
});
</script>
<?php
}
}
虽然这适用于结帐页面,但是否有人知道如何使用购物车/篮子运输计算器来实现此功能?
【问题讨论】:
-
客户可以添加更多不同邮政编码的产品到购物车吗?
-
对不起@LoicTheAztec,你是对的,我应该把它包括在内。已更新。
-
@VincenzoDiGaetano 不,送货邮政编码将保持不变。客户一次只能结帐一种产品。谢谢。
-
只是在这一点上的观察......现在我已经有了与结帐页面一起使用的代码,我注意到如果我转到结帐页面并返回购物车/购物篮,运费计算器已更新以显示客人邮政编码。
标签: php wordpress woocommerce