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

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.

Say Hello to 200 Themes

Jetpack Professional now bundles 200+ Premium WordPress themes,
alongside business class security tools, and marketing automation.

Use code "PRO" at checkout for 50% introductory discount.