问题描述
以下代码将自定义字段添加到管理产品设置中,以在产品级别管理来宾结帐:
The following code add a custom field to admin product settings to manage guest checkout at product level:
// Display Guest Checkout Field
add_action( 'woocommerce_product_options_general_product_data', 'woo_add_custom_general_fields' );
function woo_add_custom_general_fields() {
global $woocommerce, $post;
echo '<div class="options_group">';
// Checkbox
woocommerce_wp_checkbox( array(
'id' => '_allow_guest_checkout',
'wrapper_class' => 'show_if_simple',
'label' => __('Checkout', 'woocommerce' ),
'description' => __('Allow Guest Checkout', 'woocommerce' )
) );
echo '</div>';
}
// Save Guest Checkout Field
add_action( 'woocommerce_process_product_meta', 'woo_add_custom_general_fields_save' );
function woo_add_custom_general_fields_save( $post_id ){
$woocommerce_checkbox = isset( $_POST['_allow_guest_checkout'] ) ? 'yes' : 'no';
update_post_meta( $post_id, '_allow_guest_checkout', $woocommerce_checkbox );
}
// Enable Guest Checkout on Certain products
add_filter( 'pre_option_woocommerce_enable_guest_checkout', 'enable_guest_checkout_based_on_product' );
function enable_guest_checkout_based_on_product( $value ) {
if ( WC()->cart ) {
$cart = WC()->cart->get_cart();
foreach ( $cart as $item ) {
if ( get_post_meta( $item['product_id'], '_allow_guest_checkout', true ) == 'yes' ) {
$value = "yes";
} else {
$value = "no";
break;
}
}
}
return $value;
}
但是实际上不起作用.我做错了什么?我该如何解决?
But it doesn't work actually. What I am doing wrong? How can I fix it?
我正在尝试允许客人购买特定产品.管理员自定义字段显示和保存的自定义字段值在(前两个功能)中有效,但是即使购物车中有不允许客人使用的产品,也不会在结帐页面上显示登录/注册信息结帐.
I am trying to allow guest purchases for specific products. The admin custom field display and save custom field value is working (the 2 first functions), But login/register never comes up on checkout page, even if there are products in cart that doesn't allow guest checkout.
推荐答案
过滤器挂钩 enable_guest_checkout_based_on_product
不再存在,并已由另一个稍有不同的挂钩代替.
The filter hook enable_guest_checkout_based_on_product
doesn't exist anymore and has been replaced by another hook a bit different.
因此您的代码将是:
add_filter( 'woocommerce_checkout_registration_required', 'change_tax_class_user_role', 900 );
function change_tax_class_user_role( $registration_required ) {
if ( ! WC()->cart->is_empty() ) {
$registration_required = false; // Initializing (allowing guest checkout by default)
// Loop through cart items
foreach ( WC()->cart->get_cart() as $item ) {
// Check if there is any item in cart that has not the option "Guest checkout allowed"
if ( get_post_meta( $item['product_id'], '_allow_guest_checkout', true ) !== 'yes' ) {
return true; // Found: Force checkout user registration and exit
}
}
}
return $registration_required;
}
代码进入您的活动子主题(或活动主题)的functions.php文件中.应该可以.
Code goes in functions.php file of your active child theme (or active theme). It should works.
相关的续篇: 在WooCommerce中允许非结帐访客重定向
这篇关于仅在WooCommerce中允许来宾结帐特定产品的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!