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.

Code Updated to reflect the changes in the plugin where they changed the name of the custom field. Thanks Tajim for letting us know in the comments.

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.

  <?php  $args = array( 'post_type' => 'event', 'posts_per_page' => 15, 'order' => 'ASC', 'meta_key' => '_expiration-date', 'orderby' => 'meta_value' );  $eventloop = new WP_Query( $args );  if ( $eventloop->have_posts() ) : while ( $eventloop->have_posts() ) : $eventloop->the_post();    //All the Loop Content Goes Here    endwhile;  endif;  ?>  

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:

Sort Posts by Post Expiration (Event Example)

Note in order for this to work, you MUST use the Post Expirator Plugin.

If you have any questions, feel free to ask in the comments below.