Family Encyclopedia >> Electronics

How to Sort WordPress Posts by Expiration Date: Expert WP_Query Guide

As seasoned WordPress developers, we've long recommended the Post Expirator plugin for automatically expiring posts—ideal for event listing sites. It not only hides expired events effortlessly but also enables sorting by expiration date. In this guide, we'll walk you through sorting posts by due date using a custom WP_Query.

Update: We've revised the code to match the plugin's updated custom field name. Thanks to Tajim for the heads-up in the comments.

In a recent project for a non-profit hosting monthly events, we used a custom post type called 'evento'. We added this loop to their events page, but it works anywhere—sidebars, archives, or custom templates.

$args = array(
    'post_type' => 'evento',
    '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();
    // Your loop content goes here
endwhile; endif;
wp_reset_postdata();

The key is specifying meta_key as '_expiration-date' and orderby as 'meta_value'. ASC order displays the soonest-expiring events first. Here's how our event list looked:

How to Sort WordPress Posts by Expiration Date: Expert WP_Query Guide

Important: This requires the Post Expirator plugin to add the expiration meta field.

Questions? Drop them in the comments—we're here to help.