This Pro tutorial shows how the new Element Conditions API added in Bricks builder v1.8.4 can be used to register a custom condition that enables us to render elements in the search results template depending on whether there is at least one search result or not.


Applying the condition on a Section that has a query loop for showing a grid of (matching) posts:

Applying the condition on a Section that should be output only when there are no search results:

Add the following in child theme‘s functions.php or a code snippets plugin:
add_filter( 'bricks/conditions/groups', function ( $groups ) {
$groups[] = [
'name' => 'bl_conditions_group',
'label' => esc_html__( 'Custom Group', 'my-plugin' ),
];
return $groups;
});
add_filter( 'bricks/conditions/options', function( $options ) {
$options[] = [
'key' => 'bl_at_least_1_search_result',
'label' => esc_html__( 'At Least 1 Search Result', 'my-plugin' ),
'group' => 'bl_conditions_group',
'compare' => [
'type' => 'select',
'options' => [
'==' => esc_html__( 'is', 'my-plugin' ),
],
'placeholder' => esc_html__( 'is', 'my-plugin' ),
],
'value' => [
'type' => 'select',
'options' => [
'present' => esc_html__( 'Present', 'my-plugin' ),
'not_present' => esc_html__( 'Not present', 'my-plugin' ),
],
],
];
return $options;
});
add_filter( 'bricks/conditions/result', function ( $result, $condition_key, $condition ) {
// If $condition_key is not 'bl_at_least_1_search_result', we return the $render as it is
if ( $condition_key !== 'bl_at_least_1_search_result' ) {
return $result;
}
// If compare is empty, we set it to '==' as default
// If user value is empty, we set it to 'present' as default
$compare = $condition['compare'] ?? '==';
$user_value = $condition['value'] ?? 'present';
// Get the number of search results
global $wp_query;
$search_results_count = $wp_query->found_posts;
// Return true or false depending on the chosen value
return $user_value === 'present' ? $search_results_count > 0 : $search_results_count === 0;
}, 10, 3 );
Refresh the editor and apply the newly added condition.