在 WooCommerce 中显示特定用户角色的促销价格

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

在网上商店中,我想为特定客户群推出%折扣。

我已经创建了一个新组和客户,并添加了下面的代码,这为购物车提供了折扣。

/* discount biblioteka */
add_action( 'woocommerce_cart_calculate_fees', 'discount_based_on_user_role', 20, 1 );
function discount_based_on_user_role( $cart ) {
    if ( is_admin() && ! defined( 'DOING_AJAX' ) )
        return; // Exit
    
    // only for 'biblioteka' role
    if ( ! current_user_can('biblioteka') )
        return; // Exit

    // Kortings percentage
    $percentage = 40;
    
    $discount = $cart->get_subtotal() * $percentage / 100; // Calculation
    
    // Applying discount
    $cart->add_fee( sprintf( __("biblioteka discount (%s)", "woocommerce"), $percentage . '%'), - $discount, true );
}

我希望此折扣也作为促销价格显示在商店中,我添加了下面的代码,这使得网站停止工作。


/* Custom prices by user role */
add_filter('woocommerce_product_get_price', 'custom_price_assign', 10, 2);
add_filter('woocommerce_product_variation_get_price', 'custom_price_assign', 10, 2); // For product variations (optional)

function custom_price_assign( $price, $product ) {
    // Check if the user has a role of wholesaler
    if ( current_user_can('biblioteka') ){
        return $price * 0.40;
    }
    return $price;
}

针对特殊用户群体显示正常价格和 40% 折扣作为促销价的最简单方法是什么?

php woocommerce product price discount
1个回答
0
投票

尝试使用以下修改后的代码,它将显示商店中的折扣产品价格和单品:

// Conditional function: Targeting specific user role
function is_biblioteka_role() {
    global $current_user;
    return in_array( 'biblioteka', $current_user->roles );
}

// Display discounted product price in shop and single product.
add_filter( 'woocommerce_get_price_html', 'user_role_product_discounted_price_html', 20, 2 );
function user_role_product_discounted_price_html( $price_html, $product ) {
    // Targeting specific user role
    if ( ! is_biblioteka_role() ) return $price_html;

    $percentage = 40; // Kortings percentage
    $price = $product->get_price();

    // Only for prices greater than zero
    if ( ! ($price > 0) ) return $price_html;

    $regular_price    = wc_get_price_to_display( $product );
    $discounted_price = wc_get_price_to_display( $product, array( 'price' => ($price * (100 - $percentage) / 100) ) );
    return wc_format_sale_price( $regular_price, $discounted_price ) . $product->get_price_suffix();
}

// Cart subtotal discount
add_action( 'woocommerce_cart_calculate_fees', 'discount_based_on_user_role', 20, 1 );
function discount_based_on_user_role( $cart ) {
    if ( is_admin() && ! defined( 'DOING_AJAX' ) ) return; // Exit
    if ( ! is_biblioteka_role() ) return; // Targeting specific user role

    $percentage = 40; // Kortings percentage
    $cart->add_fee(
        sprintf( __("Biblioteka discount (%s)", "woocommerce"), $percentage.'%'), 
        -($cart->get_subtotal() * $percentage / 100), true 
    );
}

代码位于子主题的functions.php 文件中(或插件中)。已测试并有效。

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