Halloween Sale 15% off Ends in See the plans
PHP

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.

Don’t have WPIDE yet? Install it on your site

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

  1. Install WPIDE on your WordPress site (it is free) and open Code Snippets.
  2. Use snippet above adds it from the library in one click. Or copy the code into a new snippet with the same code type.
  3. It is added inactive: review the code and settings, then switch it on.

Have a snippet worth sharing?

Publish it to the library from WPIDE or right here. Sign in with any WordPress site that runs WPIDE, free or Pro. Public snippets are reviewed by the WPIDE team before they appear.

Which site should get this snippet?

Enter the address of your WordPress site. WPIDE opens there in a new tab with the snippet ready to review and save.

Remembered in this browser only, so you are asked once.

Report this snippet

Tell the WPIDE team what is wrong: broken code, something harmful, spam or copied work.