[英]Apply discount on products within specific category (WooCommerce)
我有這個代碼可以完美運行,並為“訂閱者”類別的用戶提供 10% 的折扣。 現在我想修改代碼,使折扣僅適用於特定類別的產品。
例如,我有三類產品:“產品”、“獨家產品”和“訂閱”。 折扣應僅適用於前兩個類別的產品,不適用於“訂閱”類別中的產品。
有人可以幫我修改這個 function 以滿足這些要求嗎?
// Applying conditionally a discount for a specific user role
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 'subscriber' user role
if ( ! current_user_can('subscriber') )
return; // Exit
// HERE define the percentage discount
$percentage = 10;
$discount = $cart->get_subtotal() * $percentage / 100; // Calculation
// Applying discount
$cart->add_fee( sprintf( __("Discount (%s)", "woocommerce"), $percentage . '%'), -$discount, true );
}
首先current_user_can('subscriber')
是檢查當前用戶角色的錯誤方法。 current_user_can
應該只用於檢查功能而不是用戶角色。
其次,您沒有很好地解釋您的類別匹配條件。 我不確定您是否要檢查是否所有產品都應該具有匹配的類別,或者其中一個應該具有,或者 1 個僅包含 1 個產品匹配的類別就可以了。 你需要自己解決這個問題。
下面的代碼正在檢查一個購物車產品是否有任何匹配的類別,那么條件將是有效的。
注意:代碼未經測試,如果您發現任何嚴重或語法錯誤,請告訴我,我將修復代碼。 如果在添加代碼后出現任何錯誤並且您無法訪問 wordpress 后端,請確保您有網站備份和 FTP 訪問權限以更改文件。
/**
* Applying conditionally a discount for a specific user role.
*/
function discount_based_on_user_role() {
if ( is_admin() && ! defined( 'DOING_AJAX' ) ) {
return;
}
// Only for logged in users.
if ( ! is_user_logged_in() ) {
return;
}
$user = get_userdata( get_current_user_id() );
// User or user roles not found.
if ( ! $user || ! $user->roles ) {
return;
}
// Only for 'subscriber' user role.
if ( ! in_array( 'subscriber', (array) $user->roles, true ) ) {
return;
}
// Get products from cart.
$products_in_cart = WC()->cart->get_cart_contents();
// Get product ids array from cart products.
$product_ids_in_cart = array_column( array_values( $products_in_cart ), 'product_id' );
// Define a flag for valid categories check.
$has_valid_categories = false;
// Define valid categories array.
$valid_categories = array( 'products', 'exclusive-products' );
// Loop through product ids.
foreach ( $product_ids_in_cart as $product_id ) {
// Check if product has any of the valid category.
if ( has_term( $valid_categories, 'product_cat', $product_id ) ) {
$has_valid_categories = true;
break;
}
}
// Valid categories not found.
if ( ! $has_valid_categories ) {
return;
}
// here define the percentage discount.
$percentage = 10;
$discount = $cart->get_subtotal() * $percentage / 100; // Calculation.
// Applying discount.
$cart->add_fee(
sprintf(
/* translators: %s Discount Value */
__( 'Discount (%s)', 'woocommerce' ),
$percentage . '%'
),
-$discount,
true
);
}
add_action( 'woocommerce_cart_calculate_fees', 'discount_based_on_user_role', 20 );
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.