I am using the code to display the coupon codes that are currently published in the shortcode from here.
The code displays a list of published coupon codes on the site.
How to get more? For example:
Any help would be appreciated.
Here's the code I'm using:
add_shortcode('ac', 'coupon_list' );
function coupon_list() {
$coupon_posts = get_posts( array(
'posts_per_page' => -1,
'orderby' => 'name',
'order' => 'asc',
'post_type' => 'shop_coupon',
'post_status' => 'publish',
) );
$coupon_codes = []; // Initializing
foreach( $coupon_posts as $coupon_post) {
$coupon_codes[] = $coupon_post->post_name;
}
// Display available coupon codes
return implode(', ', $coupon_codes) ; // always use return in a shortcode
}
[1]: https://i.sstatic.net/9sYUy.jpg
Lets assume you are storing expirydate, amount as custom fields (say coupon_expirydate, coupon_amount) then,
add_shortcode('ac', 'coupon_list' );
function coupon_list() {
$coupon_posts = get_posts( array(
'posts_per_page' => -1,
'orderby' => 'name',
'order' => 'asc',
'post_type' => 'shop_coupon',
'post_status' => 'publish',
) );
$coupon_codes = []; // Initializing
foreach( $coupon_posts as $coupon_post) {
setup_postdata( $coupon_post )
$coupon_codes[] = [
"coupon" => esc_html( get_the_title() ) //escaping html to display the title safely
"coupon_expirydate" => get_field( "coupon_expirydate" ),
"coupon_amount" => get_field( "coupon_amount" ),
"description" => get_the_content()
];
}
$coupon_codes= json_decode(json_encode($coupon_codes)); //converting to object for easy looping
// Display available coupon codes
$coupontext="<table>
<tr>
<th>Sno</th>
<th>Coupon</th>
<th>Expiry date</th>
<th>Amount</th>
<th>Description</th>
</tr>";
foreach($coupon_codes as $k=>$coupon){
$coupontext.= "<tr>
<td>".$k+1."</td>
<td>$coupon->coupon</td>
<td>$coupon->coupon_expirydate</td>
<td>$coupon->coupon_amount</td>
<td>$coupon->description</td>
</tr>";
}
$coupontext.="</table>";
return $coupontext;
}
You you want to show only non-expired coupons just use meta query variable inside arguments of get_posts().
$coupon_posts = get_posts( array(
'posts_per_page' => -1,
'orderby' => 'name',
'order' => 'asc',
'post_type' => 'shop_coupon',
'post_status' => 'publish',
'meta_query' => array(
array(
'key' => 'coupon_expirydate',
'value' => date("Y-m-d"), // Set todays date
'compare' => '>=', // Return the ones greater than todays date
'type' => 'DATE'
)
)
) );