WooCommerce优惠券字段扩展

时间:2018-10-29 18:22:33

标签: php wordpress 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”从订单金额中减去金额,有什么办法。

任何帮助将不胜感激。

1 个答案:

答案 0 :(得分:1)

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