Woocommerce код купона для персонализированного клиента - PullRequest
0 голосов
/ 21 ноября 2018

Я сгенерировал код купона динамически для каждого покупателя, когда он покупал продукт на веб-сайте, и я установил определенные условия.

Когда я динамически создал код купона, он сохраняется в разделе woocommerce> купоны.

function couponCodeGeneration($order_id, $i){
    // Get the order ID
    $coupon_code =  $order_id."".$i; // Coupon Code
    $amount = '100%'; // Amount
    $discount_type = 'percent'; // Type: fixed_cart, percent, fixed_product, percent_product

wp_coupon_exist( $coupon_code );

if( wp_coupon_exist( $coupon_code ) ) {
    //coupon code exists.
} else { 
    //coupon code not exists, so inserting coupon code
    $coupon = array(
    'post_title' => $coupon_code,
    'post_content' => '',
    'post_status' => 'publish',
    'post_author' => 1,
    'post_type'     => 'shop_coupon'
    //'post_category' => array(1)
    );

    $new_coupon_id = wp_insert_post( $coupon );

    //SET THE PRODUCT CATEGORIES
    wp_set_object_terms($post_id, 'Holiday Season offers', 'product_cat');

    // Add meta
    update_post_meta( $new_coupon_id, 'discount_type', $discount_type );
    update_post_meta( $new_coupon_id, 'coupon_amount', $amount );
    update_post_meta( $new_coupon_id, 'individual_use', 'yes' );
    update_post_meta( $new_coupon_id, 'product_ids', '' );
    update_post_meta( $new_coupon_id, 'exclude_product_ids', '' );
    update_post_meta( $new_coupon_id, 'usage_limit', '1' );
    update_post_meta( $new_coupon_id, 'expiry_date', '2019-07-31' );
    update_post_meta( $new_coupon_id, 'apply_before_tax', 'yes' );
    update_post_meta( $new_coupon_id, 'free_shipping', 'no' );
    update_post_meta( $new_coupon_id, 'limit_usage_to_x_items', '1' );
    update_post_meta( $new_coupon_id, 'usage_limit_per_user', '1' );
    update_post_meta( $post_id, 'times', '1' );


    echo '<div class="couponCode"><strong>Your Coupon Code for your next purchase - '.$coupon_code.'</strong><hr></div>';
}

}

Мне нужна помощь в следующей ситуации.

Сгенерированный код купона не должен использоваться другим клиентом.Купон только личный для этого клиента.Код купона не может быть передан.

Когда клиент размещает заказ, сгенерированный код купона не сохраняется на странице заказов администратора.Как узнать, какой код купона генерируется каким клиентом.

Может кто-нибудь дать мне предложения.

Ответы [ 2 ]

0 голосов
/ 11 декабря 2018

Я исправил свою проблему.

Добавьте следующий код в functions.php

add_filter( 'woocommerce_coupon_is_valid', 'wc_riotxoa_coupon_is_valid', 20, 2 );

if ( ! function_exists( 'wc_riotxoa_coupon_is_valid' ) ) {

    function wc_riotxoa_coupon_is_valid( $result, $coupon ) {
        $user = wp_get_current_user();

        $restricted_emails = $coupon->get_email_restrictions();

        return ( in_array( $user->user_email, $restricted_emails ) ? $result : false );
    }
}

Ref: https://gist.github.com/riotxoa/f4f1a895052c195394ba4841085a0e83

0 голосов
/ 24 ноября 2018

Начиная с Woocommerce 3 ваш код действительно устарел, с множеством ошибок.wp_coupon_exist() функция не существует.

Чтобы ограничить купон конкретным клиентом, вы можете использовать Ограничения по электронной почте WC_Coupon метод , который также позволит вам узнать, какойклиент сгенерировал код купона.

При необходимости вы также можете установить некоторые пользовательские метаданные, сохранив идентификатор пользователя или полное имя пользователя.

Итак, в моем коде есть две функции:

  • Первая, которая проверяет, не существует ли код купона
  • Вторая, которая генерирует код купона, как вы запланировали.

Код:

// 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;
}


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'; // Type
        $coupon_amount  = '100'; // Amount
        $customer_email = array( $order->get_billing_email() ); // Customer billing email
        $product_categories_names = array('Holiday Season offers');
        $date_expires = '2019-07-31';

        // 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( 'percent' );
        $coupon->set_amount( 100 );
        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");
}

Код помещается в файл function.php вашей активной дочерней темы (или активной темы).протестировано и работает.

Вы получите что-то вроде (при создании купона):

Ваш код купона для вашей следующей покупки 1198A

Или, если купон существует:

Извините, код купона уже существует.

...