首页 > 解决方案 > 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”从订单金额中减去金额,有什么办法吗?

任何帮助,将不胜感激。

标签: phpwordpresswoocommerce

解决方案


优惠券也是自定义帖子。要将您的礼品卡令牌/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' );
}

推荐阅读