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 );
Posted in Code snippets | Tagged , , , , | Comments Off on Top Posts & Pages Widget: Remove all Popular posts that weren’t published within the last month

Unlimited Video Hosting

Jetpack Premium now provides unlimited use of our video CDN. Save on hosting storage and bandwidth costs by streaming fast, ad-free video from our global network.

Learn More