woocommerce优惠券 - 获取所有列出的产品ID

时间:2015-06-07 15:00:15

标签: wordpress woocommerce

我在一个网站上工作,当有人注册我有代码时生成优惠券 -

$coupon_code =  "ex".$resulted_coupon_code ;// Code

$amount = '20'; // Amount
$discount_type = 'percent_product'; // 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_po st_meta( $new_coupon_id, 'individual_use', 'yes' );
update_post_meta( $new_coupon_id, 'product_ids', '4454,4452,4451,4449' );
update_post_meta( $new_coupon_id, 'exclude_product_ids', '' );
update_post_meta( $new_coupon_id, 'usage_limit', '1' );
update_post_meta( $new_coupon_id, 'usage_limit_per_user', '1' );
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' );
update_post_meta( $new_coupon_id, 'customer_email', $user_email );

现在我怎样才能获得优惠券产品ID? 喜欢这个

update_post_meta($ new_coupon_id,' product_ids',' 4454,4452,4451,4449');

我想检索这些4454,4452,4451,4449

2 个答案:

答案 0 :(得分:2)

WooCommerce将这些值存储在postmeta表中,因此您可以使用get_post_meta()来检索产品ID。

get_post_meta( $new_coupon_id, 'product_ids', true );

首先获取所有优惠券帖子类型,然后遍历它们以获取产品,然后循环遍历它们以获得产品帖子类型,您将使用以下内容:

// get all coupons that are published 
$coupons = get_posts( array(
    'posts_per_page'   => -1,
    'post_type'        => 'shop_coupon',
    'post_status'      => 'publish',
) );

// loop through the coupons
foreach ( $coupons as $coupon ){
    // get the product ids meta value
    $product_ids = get_post_meta( $coupon->ID, 'product_ids', true );
    // make sure something has been saved
    if ( !empty( $product_ids ){
        // convert from comma separated string to array
        $id_list = explode( ',', $product_ids );
        // loop over each ID
        foreach( $id_list as $product_id ){
            // get the product for each ID
            $product = get_post( $product_id );
            // each product associated 
        }
    }
}

答案 1 :(得分:1)

update_post_meta( $new_coupon_id, 'product_ids', get_post_meta( 4461, 'product_ids', true ));

尝试使用该代码