Wordpress

How to Sort Posts by Post Expiration Date in WordPress

In the past, we have shared how to expire posts in WordPress using the Post Expirator Plugin. Well, when creating an event listing site, we found this plugin to be super helpful. We can easily delete the event listings that are expired. Secondly, thanks to this plugin, it is really easy to sort posts by post expiration date as well. In this article, we will show you how to sort posts by post expiration date in WordPress.

In our particular project, we had Events as a Custom Post Type. Now this is for a non-profit that holds like one event per month, so we simply created a loop to put in their events page. You can use the code in your sidebar, or anywhere else you want.

01 <?php
02 $args = array( 'post_type' => 'event', 'posts_per_page' => 15, 'order' => 'ASC', 'meta_key' => 'expiration-date', 'orderby' => 'meta_value' );
03 $eventloop = new WP_Query( $args );
04 if ( $eventloop->have_posts() ) : while ( $eventloop->have_posts() ) : $eventloop->the_post();
05
06 //All the Loop Content Goes Here
07
08 endwhile;
09 endif;
10 ?>

The trick is to utilize the meta_key and then user oderby meta_value. Putting it in Ascending Order shows the event that is coming soon (expiring soonest). Example of our events listing:

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s