0

Здравствуйте.

У меня вопрос к знатокам php и Api wordpress и woocommerce.

  1. Мне надо, чтобы при регистрации пользователя автоматически создавался купон.
  2. Чтобы имя купона можно было брать из моего пользовательского поля, которое я добавил при регистрации woocommerce.

В Интернете за что можно зацепиться, нашел только вот этот код:

$coupon_code = 'UNIQUECODE'; // Code
$amount = '10'; // Amount
$discount_type = 'fixed_cart'; // Type: fixed_cart, percent, fixed_product, percent_product

$coupon = array(
    'post_title' => $coupon_code,
    'post_content' => '',
    'post_status' => 'publish',
    'post_author' => 1,
    'post_type'     => 'shop_coupon'
);

$new_coupon_id = wp_insert_post( $coupon );

// 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', 'no' );
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', '' );
update_post_meta( $new_coupon_id, 'expiry_date', '' );
update_post_meta( $new_coupon_id, 'apply_before_tax', 'yes' );
update_post_meta( $new_coupon_id, 'free_shipping', 'no' );

Все бы ничего, возможно, с этим можно было бы работать, но при вставке его в functions.php
он просто бесконечно генерирует эти купоны, причем по два за раз, и я не могу задать какие-то свои условия, может, я куда-то не туда вставляю этот код? Кто может помочь разобраться? Заранее спасибо!

1 ответ 1

1

Этот код нужно обернуть в функцию и привязать к хуку, который срабатывает после успешного создания пользователя.

add_action('user_register', 'creat_coupon_for_new_user', 10, 1);

function creat_coupon_for_new_user($user_id) {

  $coupon_code = 'UNIQUECODE'; // Code
  $amount = '10'; // Amount
  $discount_type = 'fixed_cart'; // Type: fixed_cart, percent, fixed_product, percent_product

  $coupon = array(
    'post_title' => $coupon_code,
    'post_content' => '',
    'post_status' => 'publish',
    'post_author' => 1,
    'post_type' => 'shop_coupon'
  );

  $new_coupon_id = wp_insert_post($coupon);

  // 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', 'no');
  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', '');
  update_post_meta($new_coupon_id, 'expiry_date', '');
  update_post_meta($new_coupon_id, 'apply_before_tax', 'yes');
  update_post_meta($new_coupon_id, 'free_shipping', 'no');
}

Ваш ответ

By clicking “Отправить ответ”, you agree to our terms of service and acknowledge you have read our privacy policy.

Всё ещё ищете ответ? Посмотрите другие вопросы с метками или задайте свой вопрос.