Query Loop Block: Only Posts From the Last 30 Days
Limits any Query Loop block with the class "wpide-recent" to posts published in the last 30 days, for "This month" or "Fresh this week" sections.
Opens WPIDE on
Code
// How many days back to show.
$wpide_query_recent_days = 30;
$wpide_query_recent = array( 'active' => false );
add_filter( 'pre_render_block', function ( $pre, $parsed ) use ( &$wpide_query_recent ) {
if ( 'core/query' === $parsed['blockName'] ) {
$classes = isset( $parsed['attrs']['className'] ) ? ' ' . $parsed['attrs']['className'] . ' ' : '';
$wpide_query_recent['active'] = false !== strpos( $classes, ' wpide-recent ' );
}
return $pre;
}, 10, 2 );
add_filter( 'query_loop_block_query_vars', function ( $query ) use ( &$wpide_query_recent, $wpide_query_recent_days ) {
if ( ! $wpide_query_recent['active'] ) {
return $query;
}
$date_query = isset( $query['date_query'] ) ? (array) $query['date_query'] : array();
$date_query[] = array( 'after' => absint( $wpide_query_recent_days ) . ' days ago', 'inclusive' => true );
$query['date_query'] = $date_query;
return $query;
} );
Notes
Change the number of days at the top. Use the class wpide-recent on the Query Loop block.
How to add this snippet
- Install WPIDE on your WordPress site (it is free) and open Code Snippets.
- Use snippet above adds it from the library in one click. Or copy the code into a new snippet with the same code type.
- It is added inactive: review the code and settings, then switch it on.