Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save 10horizons/bbfb7a7c26150379d79f9b630608a762 to your computer and use it in GitHub Desktop.
Save 10horizons/bbfb7a7c26150379d79f9b630608a762 to your computer and use it in GitHub Desktop.
Display all Woocommerce products eligible for coupons created with Woocommerce
<?php
/*
URL: https://wproot.dev/blog/woocommerce-display-all-products-eligible-for-coupons/
*/
$args = array(
'posts_per_page' => -1, //show all posts
'post_type' => 'shop_coupon', //custom post type
'post_status' => 'publish', //published coupons only
);
$coupons = get_posts( $args ); //array
$coupon_ids = array();
foreach ( $coupons as $coupon ) {
$coupon_id = $coupon->ID;
$expdate = get_post_meta($coupon_id, 'expiry_date', true);
$today = date('Y-m-d');
if ( strtotime($expdate) > strtotime($today) ){
array_push( $coupon_ids, $coupon_id ); //push all coupon id into an array
}
}
$n = 1;
foreach ( $coupon_ids as $active_coupon_id ) {
${'coupon'.$n.'_prod_ids'} = array();
$str = get_post_meta($active_coupon_id, 'product_ids', true);
//str is NOT an array, product ids are stored like so: '10,15,24'.
${'coupon'.$n.'_prod_ids'} = explode(",",$str);
$n++;
}
$product_ids_with_coupons = array();
$i = 1;
while ($i < $n) {
foreach ( ${'coupon'.$i.'_prod_ids'} as ${'coupon'.$i.'_prod_id'} ) {
array_push($product_ids_with_coupons, ${'coupon'.$i.'_prod_id'});
}
$i++;
}
/* Usage example */
if ( $product->product_type == 'simple' ) {
$product_obj = new WC_Product($currentpostid);
foreach ( $product_ids_with_coupons as $product_id_with_coupon ) {
if ($product_id_with_coupon == $currentpostid) {
//do something here like displaying a 'discount with coupon' image
break;
}
}
}
?>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment