每年限制购买一种产品类别 Woocommerce

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

我在上一篇文章中找到了此代码:限制客户在 WooCommerce 中的特定时间范围内多次购买特定产品,并进行自定义以限制每年购买每个类别的产品(常规 3 次,特殊促销 1 次) ,但它不起作用。谁能看一下并让我知道问题出在哪里?蒂亚!

function action_woocommerce_checkout_process() {
    // Initialize
    $customer_email = '';
    
    // Get email
    if ( is_user_logged_in() ) {
        // Get current user
        $user = wp_get_current_user();
        
        // Get email
        $customer_email = $user->user_email;
    } elseif ( isset( $_POST['billing_email'] ) && ! empty ( $_POST['billing_email'] ) ) {
        $customer_email = $_POST['billing_email'];  
    } else {
        // Get billing_email
        $customer_email = WC()->customer->get_billing_email();
    }
    
    // NOT empty
    if ( ! empty ( $customer_email ) ) {      
        $time_in_years = 1;
        $limit = 1;
        $product_cat = 'regular'; 'special-promo';
       
        $orders_last_year_by_customer_email = wc_get_orders( array(
            'date_created'  => '>' . (time() - $time_in_years ),
            'customer'      => $customer_email,
        ));
        
        // Total (counter)
        $total = 0;
        
        // Iterating through each order
        foreach ( $orders_last_year_by_customer_email as $order ) {
            // Going through order items
            foreach ( $order->get_items() as $item ) {
                // Get product ID
                $product_id = $item->get_product_id();
                
                // Compare
                if ( $specific_product_id == $product_id ) {
                    // Get quantity
                    $quantity = $item->get_quantity();
                    
                    // Add to total
                    $total += $quantity;
                }
            }
        }

        // Show error when total >= limit
        if ( $total >= $limit ) {
            wc_add_notice( sprintf( __( 'Sorry, you can only purchase one time per year', 'woocommerce' ), $limit, $specific_product_id ), 'error' );
        }       
    }
}
add_action( 'woocommerce_checkout_process', 'action_woocommerce_checkout_process', 10, 0 );
woocommerce
1个回答
0
投票

time() 是从 Unix 纪元开始的秒数测量

https://www.php.net/manual/en/function.time.php

在您的代码中,您将从当前时间(以秒为单位)中减去 1。本质上是回顾 1 秒的时间。

错了

'date_created'  => '>' . (time() - $time_in_years )

你需要做的是使用一年前的 Unix 时间(以秒为单位)

'date_created'  => '>' . (strtotime("-1 year") )
© www.soinside.com 2019 - 2024. All rights reserved.