Ajit Bhandari
Ajit Bhandari

Reputation: 1159

woocommerce coupon - get all listed products ids

I working on a website that generate coupon when someone register i have code it -

$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 );

now how can i to get the coupon products ids ?? like from this

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

i want to retrieve these 4454,4452,4451,4449

Upvotes: 2

Views: 2729

Answers (2)

Raman Singh
Raman Singh

Reputation: 161

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

try to use that code

Upvotes: 1

doublesharp
doublesharp

Reputation: 27657

WooCommerce is storing these values in the postmeta table, so you can use the get_post_meta() to retrieve the product IDs.

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

To get all of the coupon post types first, then loop over them to get the products, then loop over them to get the product post types, you would use the following:

// 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 
        }
    }
}

Upvotes: 3

Related Questions