Я хотел бы создать купон, если человек потратил более 750 долларов.
Я думал, что смогу отобразить купон на странице оформления заказа или, возможно, по электронной почте. Срок действия купона составляет 12 месяцев с даты выпуска.
Я нашел очень полезный код, который я собрал во что-то, что, как я считаю, должно работать, но он не
Я был бы очень благодарен за указатель на то, где я мог бы пойти не так.
Сначала я хочу посмотреть, потратил ли клиент более 750 долларов, если он извлечет идентификатор пользователя, идентификатор заказа и отправит к генерации кода купона
// Function to work out if a customer is a VIP
function ch_cust_is_a_vip()
{
if (ch_get_customer_spend() > 750)
{
$ch_order = wc_get_order( $order_id ); // get current order_id
$ch_user = get_current_user_id(); // Current user ID
coupon_code_generation( $ch_order, $ch_user );
}
}
add_filter( 'woocommerce_before_checkout_form_cart_notices', 'ch_cust_is_a_vip', 20, 2 ); // woocommerce_before_checkout_form_cart_notices
Функция для расчета расходов клиента
// function to return total customer spend
function ch_get_customer_spend()
{
global $wpdb;
$user_id = get_current_user_id(); // Current user ID
$user_purchases_total_sum = $wpdb->get_var( "
SELECT SUM(pm.meta_value) FROM {$wpdb->prefix}postmeta as pm
INNER JOIN {$wpdb->prefix}posts as p ON pm.post_id = p.ID
INNER JOIN {$wpdb->prefix}postmeta as pm2 ON pm.post_id = pm2.post_id
WHERE p.post_status LIKE 'wc-completed' AND p.post_type LIKE 'shop_order'
AND pm.meta_key LIKE '_order_total' AND pm2.meta_key LIKE '_customer_user'
AND pm2.meta_value LIKE $user_id " );
return $user_purchases_total_sum;
}
И генерация кода купона, я обнаружил, что это объявление только что добавило 12 месяцев дата истечения срока действия.
// Utility function that check if coupon exist
function does_coupon_exist( $coupon_code )
{
global $wpdb;
$value = $wpdb->get_var( "
SELECT ID
FROM {$wpdb->prefix}posts
WHERE post_type = 'shop_coupon'
AND post_name = '".strtolower($coupon_code)."'
AND post_status = 'publish'; ");
return $value > 0 ? true : false;
}
////////////////////////////////////
// custom coupon generation
///////////////////////////////////
function coupon_code_generation( $order_id, $i )
{
$coupon_code = $order_id."".$i; // Coupon Code
// Check that coupon code not exists
if( ! does_coupon_exist( $coupon_code ) )
{
// Get a new instance of the WC_Coupon object
$coupon = new WC_Coupon();
// Get the instance of the WC_Order object
$order = wc_get_order( $order_id );
## --- Coupon settings --- ##
$discount_type = 'percent'; // set the dicount Type
$coupon_amount = '30'; // set the discount Amount
$customer_email = array( $order->get_billing_email() ); // Customer billing email
$product_categories_names = array('skincare');
$date_expires = strtotime("+ 12 Months"); // put an expiry date 12 months from today
// Convert to term IDs
$term_ids = array();
foreach( $product_categories_names as $term_name )
{
if ( term_exists( $term_name, 'product_cat' ) )
$term_ids[] = get_term_by( 'name', $term_name, 'product_cat' )->term_id;
}
## --- Coupon settings --- ##
// Set the necessary coupon data
$coupon->set_code( $coupon_code );
$coupon->set_discount_type( $discount_type );
$coupon->set_amount( $coupon_amount );
if( is_array($term_ids) && sizeof($term_ids) > 0 )
$coupon->set_product_categories( $term_ids );
$coupon->set_email_restrictions( $customer_email );
$coupon->set_individual_use( true );
$coupon->set_usage_limit( 1 );
$coupon->set_usage_limit_per_user( 1 );
$coupon->set_limit_usage_to_x_items( 1 );
$coupon->set_date_expires( date( "Y-m-d H:i:s", strtotime($date_expires) ) );
// Save the data
$post_id = $coupon->save();
}
echo isset($post_id) && $post_id > 0 ? sprintf(
'<div class="couponCode"><strong>%s <code>%s</code></strong>.<hr></div>',
__("Your Coupon Code for your next purchase is", "woocommerce"), $coupon_code
) : __("Sorry, a coupon code already exist.", "woocommerce");
}
Иногда я вижу ошибку с $customer_email = array( $order->get_billing_email() );
// Email для выставления счета клиенту, но не всегда