php - WooCommerce 优惠券字段扩展
问题描述
我通过添加复选框“礼品卡”添加了新的自定义帖子类型“礼品卡”并扩展了 WooCommerce 简单产品
每当订单状态更改为“处理中”并且它包含产品类型礼品卡时,它都会通过以下代码创建新的礼品卡帖子
function status_order_processing( $order_id ) {
$order = wc_get_order( $order_id );
$items = $order->get_items();
foreach ( $items as $item ) {
$is_gift_card = get_post_meta( $item['product_id'], '_woo_giftcard', true );
if($is_gift_card == 'yes'){
$token = base64_encode(openssl_random_pseudo_bytes(32));
$token = bin2hex($token);
$hyphen = chr(45);
$uuid = substr($token, 0, 8).$hyphen
.substr($token, 8, 4).$hyphen
.substr($token,12, 4).$hyphen
.substr($token,16, 4).$hyphen
.substr($token,20,12);
$gift_card = array(
'post_title' => $uuid,
'post_status' => 'publish',
'post_type' => 'giftcard',
);
$gift_card_id = wp_insert_post( $gift_card, $wp_error );
update_post_meta( $gift_card_id, 'woo_gift_card_amount', (int)$item['total'] );
}
}
add_action( 'woocommerce_order_status_processing', 'status_order_processing' );
新帖子名称是在上述代码中生成的令牌,并将项目总数保存在元字段“woo_gift_card_amount”中。
如果我在优惠券字段中输入礼品卡帖子类型令牌并根据该帖子的元字段“woo_gift_card_amount”从订单金额中减去金额,有什么办法吗?
任何帮助,将不胜感激。
解决方案
优惠券也是自定义帖子。要将您的礼品卡令牌/uuid 用作 woocommerce 优惠券,您需要将其作为新帖子插入shop_coupon
帖子类型。
一个简单的例子(这应该放在你的status_order_processing
函数中,或者你可以使用单独的函数 - 无论哪种方式适合你):
$coupon_code = $uuid;
$amount = (int)$item['total'];
$discount_type = 'fixed_cart'; //available types: 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 );
if ( $new_coupon_id ) {
//add coupon/post 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, 'expiry_date', $expiry_date);
//update_post_meta($new_coupon_id, 'usage_limit', '1');
//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' );
}
推荐阅读
- elasticsearch - 如何过滤太长的响应?
- jquery - 表单验证:单击提交不触发验证
- spss - 为什么在 SPSS 中聚合前后的总数不同?
- javascript - 尝试导入本地 javascript 文件时出错
- python - 在 VS Code 中调试时 Python 日志文件创建失败
- java - 为什么 apache hadoop 配置模块忽略 CDATA?
- python - 在 Python 3.7 中获取类型注解
- go - 由于导入内部包,无法获取要构建的存储库的分支
- python - 单通道图像的颜色反转/失真?
- android-studio - 如何让 Picasso 的 GrayscaleTransformation 在 Android Studio 中的 Kotlin 上工作?