【发布时间】:2016-11-10 06:26:21
【问题描述】:
我正在编辑一个装箱单,它是在订单付款和包装时生成的。如果包含某个类别的产品,装箱单会自动添加一张优惠券,该优惠券也会打印在其上。
我的问题是,每次我刷新或重新打开装箱单时,都会使用相同的优惠券代码生成新的优惠券。所以我想实现一个规则,检查 coupon_code 是否已经存在。
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' );
*/
}
}
所以我想在wp_insert_post($coupon) 之前添加一个if 语句,所有这些代码只有在带有coupon_code 的优惠券不存在时才会执行。
我试过了:term_exists( $coupon_code, ‘coupons’)但这没有用。
感谢您的帮助!
【问题讨论】:
-
您好,我想说它有效。但不知何故,它什么也没做。我完全理解代码,这对我来说很有意义。但是当我将它包含在我的函数中时,什么也没有发生,没有错误,也没有对程序进行任何更改。它完美运行,每次都添加优惠券。
-
你的意思是和以前一样……这不就避免了刷新或重新打开装箱单时,重新创建具有相同ID的优惠券吗?通常我的代码不会做任何事情......它只是避免重新创建具有相同 ID 的优惠券......您可以检查数据库 wp_postmeta 表是否存在“_wcpdf_coupon”元键以获取创建此优惠券的订单......跨度>
-
是的,但我现在发现了问题。它没有更新 meta_key,因为 update_post_meta 最后没有布尔值。通过删除这个一切正常。非常感谢!我可以接受你的回答吗?还是你必须先改变它?
-
非常感谢,不用担心这个错误,我仍然非常感谢。而且我也有小孩^^
标签: php wordpress woocommerce coupon orders