In the WordPress block theme, we are not able to customize the search query with WordPress PHP filters. Instead, we need to update the default core/query block which returns the core query part of the WordPress block core functions.
The pre_get_posts filter does not work in the block theme, because there is a different functionality for the block theme to render your query output. I tried creating a variation block of the query. Added extra attributes, and custom meta query in pre_render_block hook to get search results.
block-variations.js file
const VARIATION_NAME = 'custom-search';
wp.blocks.registerBlockVariation( 'core/query', {
name: VARIATION_NAME,
title: 'Custom Search',
description: 'Search values with meta value',
icon: 'search',
attributes: {
namespace: VARIATION_NAME,
query: {
postType: 'post',
offset: 0,
filterByDate: true
},
},
isActive: [ 'namespace' ],
scope: [ 'inserter' ],
allowedControls: [ ],
innerBlocks: [
[
'core/post-template',
{},
[
[ 'core/post-title' ]
],
]
]
});
functions.php file
add_filter('pre_render_block', function ( $pre_render, $parsed_block )
{
// Verify it's the block that should be modified using the namespace
if (!empty($parsed_block['attrs']['namespace']) && 'custom-search' === $parsed_block['attrs']['namespace']) {
add_filter(
'query_loop_block_query_vars',
function ($query, $block) {
$meta_value = isset($_GET) && isset($_GET['s']) ? $_GET['s'] : '';
$query['meta_key'] = 'meta_key_name' //Meta key here;
$query['meta_value'] = $meta_value;
$query['meta_compare'] = 'LIKE';
return $query;
},
10,
2
);
}
return $pre_render;
}, 10, 2);
Is there any other way to customize search queries and results generated with core/query blocks?
Your approach to modifying the search query in a WordPress block theme using a custom block variation and the pre_render_block hook is on the right track. However, there are a few adjustments and considerations to ensure it works correctly.
Here's an updated snippet for your functions.php file:
We use the render_block_data filter to modify the block data before it gets rendered.