WordPress Query Loop Block: Custom Queries and Extending with PHP

Custom queries for the Query Loop block with PHP

The Query Loop block covers the common cases: post type, categories, tags, author, order. Many sites need one more condition: only upcoming events by a date field, products in stock, posts with a featured flag. A block variation with a namespace and two filters, one for the front end and one for the REST requests of the editor preview, adds such conditions while keeping the block editable for editors.

Problem: An events site uses the Query Loop block for “Upcoming events”. The block can filter the post type ha_event, but not “event date today or later, ordered by event date”, so past events show up and the order is by publish date.

Solution: Register a Query Loop variation with a namespace attribute in JavaScript, and in PHP extend the query of blocks with that namespace through query_loop_block_query_vars (front end, WordPress 6.1+) and rest_ha_event_query (editor preview). The editor keeps the normal controls for the post type, the number of items and pagination.

The variation

// js/event-query-variation.js, enqueued with enqueue_block_editor_assets
wp.blocks.registerBlockVariation( 'core/query', {
    name: 'ha/upcoming-events',
    title: 'Upcoming events',
    description: 'Events from today on, ordered by event date.',
    isActive: [ 'namespace' ],
    attributes: {
        namespace: 'ha/upcoming-events',
        query: {
            postType: 'ha_event',
            perPage: 6,
            inherit: false,
        },
    },
    allowedControls: [ 'taxQuery' ],
    scope: [ 'inserter' ],
    innerBlocks: [
        [ 'core/post-template', {}, [ [ 'core/post-title' ], [ 'core/post-excerpt' ] ] ],
        [ 'core/query-no-results', {}, [ [ 'core/paragraph', { content: 'No upcoming events.' } ] ] ],
    ],
} );

namespace marks every inserted block of this variation, and isActive makes the editor recognize it. allowedControls limits the inspector to the taxonomy filter; the post type and order are fixed by the variation and the PHP code.

The front end

add_filter( 'query_loop_block_query_vars', 'ha_upcoming_events_query', 10, 2 );
function ha_upcoming_events_query( array $query, WP_Block $block ): array {
    if ( 'ha/upcoming-events' !== ( $block->context['query']['namespace'] ?? '' ) ) {
        return $query;
    }
    $query['meta_key']   = 'ha_event_date';
    $query['orderby']    = 'meta_value';
    $query['order']      = 'ASC';
    $query['meta_query'] = array(
        array(
            'key'     => 'ha_event_date',
            'value'   => wp_date( 'Y-m-d' ),
            'compare' => '>=',
            'type'    => 'DATE',
        ),
    );
    return $query;
}

The filter runs for each Post Template block inside a Query Loop and receives the WP_Query arguments built from the block’s attributes. The block’s context contains the query attributes, including the namespace, so only blocks of this variation are changed. Dates stored as Y-m-d compare correctly as strings and as DATE.

The editor preview

add_filter( 'rest_ha_event_query', function ( array $args, WP_REST_Request $request ): array {
    if ( 'ha/upcoming-events' !== $request->get_param( 'ha_namespace' ) ) {
        return $args;
    }
    $args['meta_key']   = 'ha_event_date';
    $args['orderby']    = 'meta_value';
    $args['order']      = 'ASC';
    $args['meta_query'] = array( array( 'key' => 'ha_event_date', 'value' => wp_date( 'Y-m-d' ), 'compare' => '>=', 'type' => 'DATE' ) );
    return $args;
}, 10, 2 );

The editor preview loads posts through the REST API (/wp/v2/ha_event), which does not run query_loop_block_query_vars. The rest_{post_type}_query filter adapts those requests. The editor does not send the namespace by itself; the usual way is a small editor filter that adds a query argument (here ha_namespace) to the requests of blocks with the namespace, or to accept that the preview shows all events while the front end is filtered. The post type must have show_in_rest enabled.

Earlier approaches

Before WordPress 6.1, the only way was pre_render_block with a temporary query_loop_block_query_vars-like filter, or pre_get_posts on all queries: pre_get_posts. The variation concept itself was introduced with WordPress 5.8: a Query Loop variation in WordPress 5.8.

NOTE: Ordering by a meta value is a join on wp_postmeta for every query. For a few hundred events it is fine; for large sites, store the date in a custom table or cache the result list. When the variation is used with “Inherit query from template” on archives, inherit: true makes the main query apply and the filter above is not used.