Проверьте, существует ли уже купон WooCommerce

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

Моя проблема в том, что каждый раз, когда я обновляю или снова открываю упаковочный лист, создается новый купон с тем же кодом купона. Поэтому я хотел бы реализовать правило, которое проверяет, существует ли код купона уже.

add_action( 'wpo_wcpdf_after_order_details', 'wpo_wcpdf_custom_text_categories', 10, 2 );
function wpo_wcpdf_custom_text_categories ($template_type, $order) {
// collect categories from order items
$order_cats = array();
$items = $order->get_items();
foreach ($items as $item_id => $item) {
$product = $order->get_product_from_item($item);
if ($product) {
$terms = get_the_terms( $product->id , 'product_cat' );
foreach ($terms as $term) {
$order_cats[$term->term_id] = $term->name;
}
}
}
$target = array('Testtragen', 'Testtragetuch');
//
// check for your category requirement
if(count(array_intersect($order_cats, $target)) > 0 && $template_type == 'packing-slip'){
$coupon_code = $order->get_order_number();
$discount_type = 'fixed_product'; // Type: fixed_cart, percent, fixed_product, percent_product
$order_date = get_post_meta( $order->id, '_wcpdf_order_date', true );
$due_date = date_i18n( get_option( 'date_format' ), strtotime( $invoice_date . ' + 60 days') );
$email = $order->billing_email;$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' );
*/
}
}

Поэтому я хотел бы добавить if заявление перед wp_insert_post($coupon), что весь этот код выполняется только в том случае, если купон с кодом coupon_code еще не существует.

Я старался : term_exists( $coupon_code, ‘coupons’)но это не сработало.

Спасибо за вашу помощь!

2

Решение

Вот это решение, создающее особый meta_key для $order->id избегать генерации нового купона с тем же кодом купона при обновлении или повторном открытии упаковочного листа.

Вот ваш измененный код (с пояснениями к комментариям):

add_action( 'wpo_wcpdf_after_order_details', 'wpo_wcpdf_custom_text_categories', 10, 2 );
function wpo_wcpdf_custom_text_categories ($template_type, $order) {
// collect categories from order items
$order_cats = array();
$items = $order->get_items();
foreach ($items as $item_id => $item) {
$product = $order->get_product_from_item($item);
if ($product) {
$terms = get_the_terms( $product->id , 'product_cat' );
foreach ($terms as $term) {
$order_cats[$term->term_id] = $term->name;
}
}
}
$target = array('Testtragen', 'Testtragetuch');
//
// check for your category requirement
if(count(array_intersect($order_cats, $target)) > 0 && $template_type == 'packing-slip'){
$coupon_code = $order->get_order_number();
$discount_type = 'fixed_product'; // Type: fixed_cart, percent, fixed_product, percent_product
$order_date = get_post_meta( $order->id, '_wcpdf_order_date', true );
$due_date = date_i18n( get_option( 'date_format' ), strtotime( $invoice_date . ' + 60 days') );
$email = $order->billing_email;$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'
);// @@@ We create a meta_key '_wcpdf_coupon' for this order with value 'no'
if( empty( get_post_meta( $order->id, '_wcpdf_coupon', true) ) ) {
add_post_meta( $order->id, '_wcpdf_coupon', 'no', true );
}

// @@@ if this meta_key for this order has a value = 'no' was update it to 'yes'
if( get_post_meta( $order->id, '_wcpdf_coupon', true) == 'no' ) {

// Now we update it to 'yes'. This avoid the coupon be reused for this order.
update_post_meta( $order->id, '_wcpdf_coupon', 'yes');

$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' );
}
}
}

Это должно решить эту проблему …

1

Другие решения

Других решений пока нет …

По вопросам рекламы ammmcru@yandex.ru
Adblock
detector