仅允许访客在 WooCommerce 中结帐特定产品

问题描述 投票:0回答:2

以下代码将自定义字段添加到管理产品设置,以在产品级别管理访客结帐:

// 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;
}

但实际上并不起作用。我做错了什么?我该如何解决它?

我正在尝试允许客人购买特定产品。管理自定义字段显示和保存自定义字段值正在工作(第2个功能),但登录/注册永远不会出现在结帐页面上,即使购物车中有不允许访客结帐的产品。

php wordpress woocommerce checkout user-registration
2个回答
2
投票

过滤器钩子

enable_guest_checkout_based_on_product
不再存在,已被另一个有点不同的钩子取代。

所以你的代码将是:

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 文件中。应该有效。

相关延续: WooCommerce 中允许非结帐客人重定向


0
投票

如何调整代码以允许访客结帐某一产品类别(在我的例子中为“活动”)?

© www.soinside.com 2019 - 2024. All rights reserved.