How to Sort WordPress Posts by Expiration Date (2023 Expert Guide)

Are you looking for a way to automatically remove outdated content from your WordPress website? Do you want to display a list of upcoming events or limited-time offers that always stays current? Sorting your posts by expiration date is a powerful solution that can help keep your site fresh and relevant.

In this expert guide, we‘ll dive deep into how to use the free Post Expirator plugin to add expiry dates to your WordPress posts and sort them by expiration in any query or template. Whether you‘re a developer looking to enhance your themes or a marketer wanting to better automate content management, you‘ll learn everything you need to know to implement this functionality on your own site.

Understanding Post Expiration in WordPress

Before we get into the step-by-step tutorial, let‘s make sure we‘re on the same page about what post expiration is and how it works in WordPress.

Essentially, post expiration lets you set a specific date and time in the future when a post should automatically change status or be removed from your site. This is incredibly useful for time-sensitive content like:

  • Event listings and registrations
  • Job postings and applications
  • Deals, sales, and promotional offers
  • Announcements and news updates

Without post expiration functionality, you would have to manually edit or delete these types of posts after they were no longer relevant. This can be tedious and time-consuming, especially on large sites with lots of content.

Thankfully, the Post Expirator plugin makes it easy to set expiration dates on any post or custom post type in WordPress. It works by saving the expiration timestamp as a custom field value that you can then use in your theme templates and queries.

Currently, Post Expirator is active on over 100,000 WordPress sites. It‘s a popular solution for automating content management and improving performance by reducing database bloat.

How to Set Up and Configure the Post Expirator Plugin

Let‘s walk through how to install and configure the free Post Expirator plugin so you can start setting expiry dates on your WordPress posts.

Plugin Installation

  1. Log in to your WordPress admin dashboard and navigate to Plugins → Add New
  2. Search for "Post Expirator" in the plugin repository
  3. Look for the plugin by Aaron Axelsen and click Install Now
  4. After the plugin has installed successfully, click Activate

Alternatively, you can download the plugin files from the official WordPress plugin directory and upload them to your site using the "Upload Plugin" option on the Add Plugins page.

Configuration Settings

With the plugin installed and activated, you can configure its settings by going to Settings → Post Expirator in the WordPress admin sidebar. Here‘s an overview of the available options:

SettingDefaultDescription
Default expiration dateNoneSpecify a default date to be set on each new post, e.g. +30 days
Default expiration actionDraftChoose what should happen to posts when they expire – Draft, Private, Delete, or Stick (not expired)
Date/time formatY-m-d H:iSet your preferred format for displaying expiry dates
Expiration CategoriesAllIf you only want certain post categories to be managed by the plugin, specify them here
Expiration EmailDisabledEnable email notifications to alert you before a post expires

Most of the default settings will work well for the majority of sites, but feel free to customize them based on your needs. For example, you may want to change the default expiration action to Private if you don‘t want expired posts to be trashed.

When you‘re finished reviewing the settings, click Save Options at the bottom of the page. You‘re now ready to start adding expiration dates to your content!

Adding Expiration Dates to Posts

The Post Expirator plugin adds a new meta box to the Edit Post screen where you can set the expiry date and time for each piece of content. Here‘s how to use it:

  1. Create a new post or open an existing one for editing
  2. Scroll down below the post editor until you see the Post Expirator meta box
  3. Check the "Enable Post Expiration" option to activate the expiry settings
  4. Choose the desired expiration date and time using the date picker
  5. If needed, select the expiration categories and add a note about why the post is expiring
  6. Click Publish or Update to save your changes

After the specified expiration date and time have passed, the post will automatically change to the status you configured in the plugin settings. For instance, if you set the expiration action to "Draft", the post will no longer be publicly visible on your site once it expires.

Repeat these steps for each post you want to have an automatic expiration date. If you have a large number of posts to update, you can use the Quick Edit feature on the All Posts screen to modify the post expirator settings in bulk.

Sorting Posts by Expiration Date

Now that you know how to set expiration dates on your posts, let‘s explore how to actually sort and display your content by expiry date. This allows you to create things like:

  • Widgets showing the next upcoming events
  • Archive pages with job listings sorted soonest to latest
  • Countdowns of current deals and promotions
  • Automatic removal of old announcements from your news section

Since the Post Expirator plugin saves the expiration timestamp as a custom field on each post, we can use that in our WordPress queries to order and filter the results. Here‘s the basic syntax:

$args = array(
    ‘post_type‘      => ‘post‘,
    ‘posts_per_page‘ => 5,
    ‘orderby‘        => ‘meta_value‘,
    ‘meta_key‘       => ‘_expiration-date‘,
    ‘order‘          => ‘ASC‘,
    ‘meta_query‘     => array(
        array(
            ‘key‘     => ‘_expiration-date‘,
            ‘value‘   => time(),
            ‘compare‘ => ‘>=‘,
            ‘type‘    => ‘NUMERIC‘
        )
    )
);
$upcoming_posts = new WP_Query( $args );

Let‘s break down what each part of this query is doing:

  • post_type – Specifies which post type(s) to retrieve. Change ‘post‘ to your custom post type slug if needed.
  • posts_per_page – Limits the number of results. Set to -1 to return all posts.
  • orderby – Sorts posts by the value of a meta field, in this case _expiration-date.
  • meta_key – Explicitly sets which custom field to order by. Required when ordering by meta value.
  • order – Specifies the sort direction. ASC puts the closest expiration date first.
  • meta_query – Filters posts that have an _expiration-date value in the future. Compares the current Unix timestamp to the saved timestamp value.

This query will give you the 5 posts with the soonest upcoming expiration dates. You can modify the arguments as needed and loop through the results to display the posts:

if ( $upcoming_posts->have_posts() ):
    while ( $upcoming_posts->have_posts() ): 
        $upcoming_posts->the_post();
        // Display post title, excerpt, custom fields, etc.
    endwhile;
    wp_reset_postdata();
else:
    // Optional fallback if no posts found
endif;

You can use this code anywhere in your theme templates, such as:

  • sidebar.php to create an upcoming events or current promotions widget
  • archive-{post-type}.php for a custom post type archive page
  • front-page.php to display the next featured event or highlight expiring posts

Some other ways you could extend and customize the expiry query:

  • Change order to DESC to sort by furthest expiration date first
  • Add date_query parameters to limit posts to a certain timeframe, like the current month
  • Include category_name or tax_query arguments to only get posts from specific categories or taxonomies
  • Wrap the query in a function for reusability and combine it with Transients API for caching

The Post Expirator developer also provides some built-in shortcodes you can use to insert lists of upcoming or expired posts into your content without needing to write any custom code.

Managing Expired Posts

So what happens to your content after the expiration date has passed? That depends on the expiration action you configured in the plugin settings:

  • Draft – The post is unpublished and moved to Draft status
  • Private – The post is made private, so only logged-in admins and editors can view it
  • Delete – The post is sent to the Trash (or permanently deleted if Trash is disabled)
  • Stick – The post is not expired and remains published as-is

If you chose Draft or Private, the expired posts will no longer appear to site visitors but will still exist in your WordPress database. To keep your site running optimally, it‘s a good idea to periodically clean up any expired drafts or private posts you no longer need.

You can find a list of expired posts by going to the All Posts screen and selecting the "Expired" view from the filter dropdown. Bulk select the expired posts and use the Bulk Actions dropdown to delete them permanently.

On the other hand, if you set posts to be automatically deleted (or Trashed) when they expire, make sure you have a full backup of your site before relying on this option. You don‘t want to accidentally lose content forever if a post expires sooner than intended.

Expired content can bloat your database and impact site performance over time, so it‘s important to have a plan for managing it. Some other tips:

  • Use the expiration email setting if you want to be notified before a post expires
  • Assign user roles and capabilities to control who can set and modify expiration dates
  • Update your content strategy to account for expiring and protecting old posts
  • Schedule redirects from expired post URLs to newer, relevant content
  • Explore other plugins like WP-Cron Control if you need more advanced automation and scheduling options

With a little forethought and the help of the Post Expirator plugin, you can keep your WordPress site clutter-free and ensure visitors are always seeing your freshest, most current content.

Troubleshooting Post Expiration Issues

In most cases, configuring Post Expirator and sorting posts by expiration date is a straightforward process. But if you find that your posts aren‘t expiring as expected or the _expiration-date field isn‘t saving correctly, here are some troubleshooting steps to try:

  1. Double-check that you‘ve selected "Enable Post Expiration" and set a valid future date/time on the post
  2. Review your Post Expirator plugin settings and make sure the correct post type and taxonomies are selected
  3. Confirm that you‘re using the correct post type and meta field names in any custom expiry date queries
  4. Use a post meta inspector plugin to verify the _expiration-date values are being stored properly in the database
  5. Clear any page caching and object caching on your site, as this can sometimes interfere with automated post expiration
  6. Temporarily switch to a default WordPress theme like Twenty Twenty-One and retest to rule out conflicts with your custom theme files
  7. Check your WordPress error logs for any notices or warnings related to the Post Expirator plugin or meta field queries
  8. Try adjusting the WP-Cron settings on your site to ensure scheduled events like post expiration are firing correctly
  9. Consult the plugin support forums to see if other users have experienced similar issues and found solutions
  10. If all else fails, contact the plugin developer directly or hire a WordPress expert to troubleshoot your specific setup

Remember, automated post expiration is just one piece of keeping your WordPress site running smoothly. It‘s important to keep your plugins and themes up to date, implement security best practices, and regularly audit and clean up your content. Combing post expiration with other optimization techniques will ensure your site stays fast, secure, and user-friendly.

Conclusion and Next Steps

Sorting your WordPress posts by expiration date is a game-changer for managing time-sensitive content more efficiently. With the Post Expirator plugin, you can:

  • Automatically unpublish or delete posts after a specific date
  • Display upcoming or expiring posts in any query or template
  • Keep your content fresh and relevant without manual work
  • Reduce database clutter and improve site performance over time

To get started, install the free plugin and configure its settings to match your needs. Enable expiration dates on your new and existing content, then update your theme templates to sort and filter posts based on the saved _expiration-date timestamps.

By following the steps and best practices outlined in this expert guide, you‘ll be able to integrate post expiration seamlessly into your WordPress workflow. Your visitors will appreciate always seeing the most current information, and you‘ll save hours of time managing outdated posts.

For more advanced inspiration, check out these resources:

Have any lingering questions about sorting your WordPress posts by expiration date? Drop a comment below – I‘m here to help you make the most of this powerful content management technique.

Did you like this post?

Click on a star to rate it!

Average rating 0 / 5. Vote count: 0

No votes so far! Be the first to rate this post.