WP 5.8 “Query Loop” block: where to place custom query?

Looking into render_block_core_post_template() we can see it calls build_query_vars_from_query_block() (previously named construct_wp_query_args) to setup the query arguments of WP_Query from the Query` block properties.

From there I don’t see it supporting custom taxonomies for the secondary
query … yet!

Work-around-idea: For the Query Loop:

enter image description here

add a search keyword for using custom taxonomies, e.g. :query-motor-electric:

enter image description here

and write a plugin to handle this:

// Replace :query-motor-electric search keyword for a custom taxonomy query.
add_action( 'pre_get_posts', function( \WP_Query $q ) {
    if ( $q->is_search() && ':query-motor-electric' === trim( $q->get( 's' ) ) ) {
        // Custom taxonomy query.
        $tax_query = array(
            array(
                'taxonomy' => 'motor',
                'field'    => 'slug',
                'terms'    => 'electric',
            ),
        );
        $q->set( 'tax_query', $tax_query );

        // Clear search, unset search query variable or use a stop-word filter.
        $q->set( 's', '' );
    }
} );

or extend this further to support a dynamic keyword.

Example Block code for the Query Loop:

<!-- wp:query {"queryId":1,"query":{"perPage":3,"pages":1,"offset":0,"postType":"post","categoryIds":[],"tagIds":[],"order":"desc","orderBy":"date","author":"","search":":query-motor-electric","sticky":""}} -->
<div class="wp-block-query"><!-- wp:post-template -->
<!-- wp:post-title /-->

<!-- wp:post-date /-->

<!-- wp:post-excerpt /-->
<!-- /wp:post-template --></div>
<!-- /wp:query -->

where the relevant search part is:

<!-- wp:query {...,"query":{...,"search":":query-motor-electric"}} -->

Leave a Comment

tech