Top Posts & Pages Widget: Remove all Popular posts that weren’t published within the last month

Explore the benefits of Jetpack

Learn how Jetpack can help you protect, speed up, and grow your WordPress site. Get up to 70% off your first year.

Explore plans

Top Posts & Pages Widget: Remove all Popular posts that weren’t published within the last month

By default, the Top Posts widget includes all popular posts on your site in the past 2 days, even if those posts were published a long time ago. The jetpack_widget_get_top_posts filter allows you to change that, and remove all Popular posts that weren’t published within the last month.

/**
 * Remove all Popular posts that weren't published within the last month
 */
function jeherve_remove_old_top_posts( $posts, $post_ids, $count ) {
    foreach ( $posts as $k => $post ) {
        // Date when the post was published
        $post_date = strtotime( get_the_date( 'Ymd', $post['post_id'] ) );

        // If the post was published more than 30 days ago, let's remove it from the Top Posts widget
        if ( $post_date < strtotime( '-30 days' ) ) {
            unset( $posts[$k] );
        }
    }
    return $posts;
}
add_filter( 'jetpack_widget_get_top_posts', 'jeherve_remove_old_top_posts', 10, 3 );
This entry was posted in Code snippets and tagged , , , , . Bookmark the permalink.

Jeremy Herve profile
Jeremy Herve

Jetpack Mechanic 🚀 at Automattic. WordPress, board games, TV Series, music.

Explore the benefits of Jetpack

Learn how Jetpack can help you protect, speed up, and grow your WordPress site. Get up to 70% off your first year.

Explore plans

Have a question?

Comments are closed for this article, but we're still here to help! Visit the support forum and we'll be happy to answer any questions.

View support forum