programing

WooCommerce 사용자 역할 및 소규모 금액에 따른 배송 방법

telebox 2023. 10. 19. 22:15
반응형

WooCommerce 사용자 역할 및 소규모 금액에 따른 배송 방법

구매하는 사용자의 역할에 따라 두 가지 배송료를 추가해야 합니다.저에게는 '도매_고객'이라는 역할이 있으며 배송비를 지불해서는 안 됩니다.단, 카트의 합계가 €90 이하인 경우에는 구매를 방지하고 체크아웃 시 메시지를 추가해야 합니다(90유로에 도달해야 함).

다른 옵션은 카트 하위 합계가 €40 이하일 경우 5유로의 배송비를 지불해야 하는 다른 모든 WordPress 역할입니다.

저는 WooCommerce에서 배송을 구성했고, 최소 주문 금액으로 €40와 €90의 두 가지 무료 배송 방법을 만들었습니다.

문제는 'holesale_customer' 역할의 사용자가 €40에 도달하면 해당 무료 배송 방법에 대해서도 활성화된다는 점입니다. 이 사용자 역할('holesale_customer')의 배송비가 최소 €90을 초과할 경우 무료이기 때문에 발생해서는 안 됩니다.

WooCommerce에서 발송물을 다음과 같은 방법으로 구성하여 두 가지 발송 방법을 작성했습니다. - 하나는 €90의 "최소 수량 필요"를 가지고 있습니다.

  • 다른 제품은 "필요한 최소 수량"이 40유로입니다.

  • 배송비는 €0입니다.

필요한 것을 얻기 위해 다음과 같은 기능을 추가하려고 했지만, 모든 배송 방법이 항상 활성화되어 있기 때문에 "무료 배송 시 최소 40유로"라는 소매 배송 방법도 holesale_customer' 역할의 사용자에게 활성화됩니다. 이 역할을 하는 사용자는 자신의 역할이 아닌 혜택을 받을 수 있으므로 이런 일이 발생해서는 안 됩니다.

제가 테스트를 많이 했기 때문에 제가 찾던 것을 하려고 했던 코드의 일부를 보여주는 것입니다.저만 'woCommerce' 설정 이미지 보여주기 'hotelsale_customer' 역할 발표문에 언급한 내용을 추가할 방법이 없습니다.

function custom_shipping_methods_visibility( $available_methods ) {
     
        $subtotal = WC()->cart->subtotal;
        
        $user = wp_get_current_user();
        $user_roles = $user->roles;
        
        // Check user role and cart subtotal to show/hide shipping methods
        if ( in_array( 'wholesale_customer', $user_roles ) && $subtotal <= 70 ) {
            unset( $available_methods['flat_rate:13'] );
        } elseif ( $subtotal <= 30 ) {
            unset( $available_methods['flat_rate:9'] );
        }
        
        return $available_methods;
    }
    add_filter( 'woocommerce_package_rates', 'custom_shipping_methods_visibility', 10, 1 );

////////////////////

// Adds a custom function to filter shipping methods based on cart role and subtotal
    function custom_shipping_methods( $available_methods ) {
        // Get cart subtotal
        $subtotal = WC()->cart->subtotal;
        
        // Gets the role of the current user
        $user = wp_get_current_user();
        $user_roles = $user->roles;
        
        //Check user role and cart subtotal to adjust shipping methods
        if ( in_array( 'wholesale_customer', $user_roles ) && $subtotal < 70 ) {
            foreach ( $available_methods as $method_id => $method ) {
                // Hide the shipping methods if the user is a wholesaler and the subtotal is less than €70
                unset( $available_methods[ $method_id ] );
            }
            
            // Show a warning message
            wc_add_notice( 'Debes alcanzar un mínimo de 70€ en tu carrito para realizar el pedido.', 'error' );
        }
        
        return $available_methods;
    }
    add_filter( 'woocommerce_package_rates', 'custom_shipping_methods', 10, 1 );

config-1

enter image description here

구성-2:

enter image description here

구성-3:

enter image description here

구성-4:

업데이트됨

첫째, 카트 소계가 €90 미만일 경우 "도매_고객" 사용자가 주문하는 것을 방지하기 위해 다음 코드를 사용합니다.

  • 카트 및 체크아웃 페이지에 관련 알림을 표시합니다.
  • 체크아웃 유효성 확인 프로세스에 오류 알림을 표시하여 구매를 방지합니다.
// Conditional function: Is user a Wholesale Customer
function is_a_wholesale_customer() {
    if ( ! is_user_logged_in() ) return false;

    return (bool) in_array( 'wholesale_customer', wp_get_current_user()->roles );
}

// Conditional function: Is user a (normal) Customer
function is_a_normal_customer() {
    if ( ! is_user_logged_in() ) return false;

    return (bool) in_array( 'customer', wp_get_current_user()->roles );
}

// Conditional function: Is "wholesale_customer" allowed to order
function is_wholesale_customer_allowed_to_order() {
    // Check "wholesale_customer" user role and required subtotal
    return is_a_wholesale_customer() && WC()->cart->subtotal < 90 ? false : true;
}

// The notice text (for "wholesale_customer")
function wholesale_customer_text_error_notice(){
    return __('Please remember that you must reach an amount of €90', 'woocommerce');
}

// Notice reminder based on required subtotal (for "wholesale_customer")
add_action( 'woocommerce_before_cart', 'check_cart_subtotal_wholesale_customer' ); // cart
add_action( 'woocommerce_before_checkout_form', 'check_cart_subtotal_wholesale_customer' ); // checkout
function check_cart_subtotal_wholesale_customer() {
    if ( ! is_wholesale_customer_allowed_to_order() ) {
        wc_print_notice( wholesale_customer_text_error_notice() );
    }
}
// Checkout validation based on required subtotal (for "wholesale_customer")
add_action( 'woocommerce_checkout_process', 'wholesale_customer_checkout_validation' );
function wholesale_customer_checkout_validation() {
    if ( ! is_wholesale_customer_allowed_to_order() ) {
        wc_add_notice( wholesale_customer_text_error_notice(), 'error' ); // Displays an error notice
    }
}

배송 방법의 경우, 설정이 정확합니다.

다음 코드는 사용자 역할("도매_고객" 및 "고객"(로그인되지 않은 사용자도 추가)에 따라 배송 방법을 표시/숨깁니다.) 및 무료 배송을 위한 카트 하위 합계 최소 금액입니다.

업데이트: 코드는 이제 로그되지 않은 사용자와 함께 작동합니다("고객" 사용자 역할과 동일).

"도매_고객"의 경우 카트 하위 합계가 90유로에 이를 때까지 모든 배송 방법이 비활성화됩니다.

무료배송이 가능해지면 다른 모든 배송방법은 숨겨집니다.

두 가지 무료 배송 방법에 대해 각각 정확한 배송비 ID를 받아야 합니다.
카트 합계가 90유로를 초과하는 경우 체크아웃 페이지 배송 섹션에서 표시된 라디오 버튼을 각 무료 배송 옵션별로 검사합니다(아래 스크린샷 참조).

enter image description here

이제 무료 배송 방법 요금 ID 두 가지 아래의 코드를 설정할 수 있습니다.

// showing / Hidding shipping methods
add_filter( 'woocommerce_package_rates', 'filter_shipping_package_rates', 10, 2 );
function filter_shipping_package_rates( $rates, $package ) {
    // Settings
    $free_rate_ids  = array( 
        'wholesale_customer'   => 'free_shipping:2', // Here set the free shipping rate ID for wholesale user
        'customer_or_unlogged' => 'free_shipping:3', // Here set the free shipping rate ID for customer or unlogged user
    );

    $error_data['all_rates'] = array_keys($rates);
    
    // "Wholesale" user role
    if ( is_a_wholesale_customer() ) {
        $key = 'wholesale_customer';
        // show only "Wholesale" free shipping when available
        if( isset($rates[$free_rate_ids[$key]]) ) {
            return array( $free_rate_ids[$key] => $rates[$free_rate_ids[$key]] );
        } 
        // Hide all shipping methods (no free shipping available)
        else {
            return array();
        }
    } 
    // "Customer" user role or unlogged users
    else {
        $key = 'customer_or_unlogged';
        // show only "Normal" free shipping when available
        if( isset($rates[$free_rate_ids[$key]]) ) {
            return array( $free_rate_ids[$key] => $rates[$free_rate_ids[$key]] );
        } 
    } 
    return $rates;
}

코드는 기능을 합니다.활성 하위 테마(또는 활성 테마)의 php 파일입니다.테스트를 거쳐 작동합니다.

코드가 저장되면 캐시된 데이터에 저장된 배송 방법을 새로 고치려면 카트를 비워야 합니다(또는 현재 배송 영역에 대해 관련 배송 방법을 비활성화, 저장활성화, 저장).

언급URL : https://stackoverflow.com/questions/76502094/woocommerce-shipping-methods-based-on-user-roles-and-subtotal-amount

반응형