百分比折扣仅限于日期范围和 Woocommerce 中的订单计数

Percentage Discount limited to a date range and Orders count in Woocommerce

我正在尝试制作一个功能,无论购物车中有什么产品或有多少,都将购物车折扣设置为 10%。

这段代码工作正常:

function site_wide_shop_discount_with_custom_title( $cart ) {
  $discount = $cart->subtotal * 0.1;
  $cart->add_fee( __( 'YOUR TEXT HERE', 'your-text-domain' ) , -$discount );
}
add_action( 'woocommerce_cart_calculate_fees', 'site_wide_shop_discount_with_custom_title' );

我的目标是将其限制在一个日期范围和 100 个订单内。此代码(我的目标)不起作用:

function shop_discount_for_100_orders( $cart ) {

    $discountWeekStart = new DateTime('2018-10-07'); // when the discount week starts
    $dsicountWeekEnd  = new DateTime('2018-10-15'); // when the discount week ends
    $hundred_orders_discount = $cart->subtotal * 0.1; // during discount week, we give ten percent off the cart subtotal
    $hundred_orders_discount_over = $cart->subtotal; // no more discount


    if ( $discountWeekStart ) {
    $cart->add_fee( __( 'Global Discount Week', 'my-text-domain' ) , -$hundred_orders_discount );
    } else if {
        $hundred_orders_discount_over;
}
    }
add_action( 'woocommerce_cart_calculate_fees', 'shop_discount_for_100_orders' );

关于如何将折扣限制在一个日期范围内以及如何将其设置为从最后一个订单算起的 100 个订单有什么想法吗?

感谢任何想法、帮助或支持。

以下代码将有条件地设置百分比折扣,仅限于特定数量的订单计数并基于日期时间范围。

您需要定义店铺时区this time zones strings list

中选择正确的字符串

代码:

// Add a discount conditionally based on a date range for the
add_action( 'woocommerce_cart_calculate_fees', 'limited_date_range_percentage_discount' );
function limited_date_range_percentage_discount( $cart ) {
    // Your settings:
    date_default_timezone_set('Europe/Paris'); // Define the Time zone from this allowed time zones strings (http://php.net/manual/en/timezones.php)
    $start_time       = mktime('00', '00', '00', '10', '07', '2018'); // starting on "2018-10-07"
    $end_time         = mktime('23', '59', '59', '10', '15', '2018'); // Ending on "2018-10-15" (included)
    $now_time         = strtotime("now"); // Now time
    $percentage       = 10; // Discount percentage
    $max_orders_count = 100; // Limit to the first XXX orders

    $subtotal       = $cart->get_subtotal();
    $dicounts_count = get_option('wc-discounted-orders-count') ? get_option('wc-discounted-orders-count') : 0;

    if ( $now_time >= $start_time && $now_time <= $end_time && $dicounts_count <= $max_orders_count ) {
        $discount = $cart->get_subtotal() * $percentage / 100;
        $cart->add_fee( __( 'Week Discount', 'woocommerce' ) . ' (' . $percentage . '%)', -$discount );
    }
}

// Discounted orders count update
add_action('woocommerce_checkout_create_order', 'update_discounted_orders_count', 20, 2);
function update_discounted_orders_count( $order, $data ) {
    if( $orders_count = get_option('wc-discounted-orders-count') ){
        update_option( 'wc-discounted-orders-count', $orders_count + 1 );
    } else {
        update_option( 'wc-discounted-orders-count', 1 );
    }
}

代码进入您的活动子主题(活动主题)的 function.php 文件。已测试并有效。