Jetpack: Limit WordPress Related Posts To A Specific Date Range

Related posts are an essential feature for websites, especially those with significant content such as blogs and news portals. They contribute to various aspects of user experience and website performance. Here are the key reasons why related posts are important:

Implementing related posts can significantly benefit your website by enhancing user engagement, SEO performance, and overall user experience. They are a simple yet powerful tool to ensure your content remains accessible and that users continue to discover and interact with your site’s offerings.

Related Posts Date Range

I was double-checking an article I had written and noticed that the related post that came up was from 9 years ago on a platform that no longer existed. So, I decided to look deeper at the Jetpack related posts options on my site and see if I could limit the date range.

Jetpack does a fantastic job of selecting similar relevant posts, but unfortunately, it has no idea that many of the articles may be outdated. I often remove old posts that make no sense, but I don’t have time to review all 5,000 articles I’ve written for over a decade!

Unfortunately, there’s no setting on Jetpack to accomplish this; you can only set whether or not you wish to have a headline, what the headline is, and options for the layout, including whether to show thumbnails, the date, or any content.

related posts plugin jetpack

Jetpack Function For Related Posts Date Range

As with virtually everything in WordPress, though, there’s a robust API where you can customize your child theme (or theme) functions.php file and modify how it works. In this case, I want to limit the scope of any related posts to 2 years… so there’s a function that Jetpack includes that can be called:

function mtz_related_posts_limit( $date_range ) {
    $date_range = array(
        'from' => strtotime( '-2 years' ),
        'to' => time(),
    );
    return $date_range;
}

function mtz_check_and_add_jetpack_filter() {
    // Check if the Jetpack plugin is active
    if ( class_exists( 'Jetpack' ) ) {
        add_filter( 'jetpack_relatedposts_filter_date_range', 'mtz_related_posts_limit' );
    } else {
        // Handle the case when Jetpack is not active
        error_log( 'Jetpack plugin is not active. Related posts filter was not applied.' );
    }
}

// Hook onto a WordPress action that runs after all plugins are loaded
add_action( 'plugins_loaded', 'mtz_check_and_add_jetpack_filter' );

Here’s a brief explanation of what your code does:

Adding this filter to the query now ensures related posts are limited to anything written in the last two years!

There are additional ways of customizing your related posts; check out the Jetpack support page on the topic.

Exit mobile version