Getting meta query working with Post Module

Do you want to filter posts output using meta values? This tutorial helps you understand and filter meta query in Posts module of Beaver Builder.

Creating the new fields in Post Module’s settings form

Beaver builder is providing a hook “fl_builder_loop_settings_after_form”. Therefore you can add any custom field(s) in the settings form. I am adding three new fields: meta key, meta value and compare under the Post module’s Content tab.

Open functions.php file of your child theme and add the following snippet

Adds Custom fields

// Add Custom Fields to BB Post Module
add_action( 'fl_builder_loop_settings_after_form', function ( $settings ) {
	echo '
' . "n"; echo '
' . "n"; echo '' . "n"; echo '
' . "n"; echo '
' . "n"; echo '' . "n"; FLBuilder::render_settings_field('meta_key', [ 'type' => 'text', 'label' => __( 'Key', 'fl-builder' ), ], $settings ); FLBuilder::render_settings_field('meta_value', [ 'type' => 'text', 'label' => __( 'Value', 'fl-builder' ), ], $settings ); FLBuilder::render_settings_field('meta_compare', [ 'type' => 'select', 'label' => __('Compare', 'fl-builder'), 'options' => [ '=' => __('Is equal to', 'fl-builder'), '!=' => __('Is not equal to', 'fl-builder'), ' __('Is less than', 'fl-builder'), ' __('Is less than or equal to', 'fl-builder'), '>' => __('Is greater than', 'fl-builder'), '>=' => __('Is greater than or equal to', 'fl-builder'), ], ], $settings ); echo '
' . "n"; echo '
' . "n"; echo '
'; });

Preview: Posts Settings Content Tab

Meta Field

 

Creating the new WP_Query object

Post Module is calling the FLBuilderLoop::query() method. It is building two types of query: main wp query and custom query. In this method have a filter “fl_builder_loop_query”. So you can overwrite the default query object and create a new custom object as per your requirement.

Again the open the functions.php file of your theme and add this snippet at end of the file

Creates custom query object

add_filter( 'fl_builder_loop_query', function( $query, $settings ) {

	if( ! empty( $settings->meta_key ) && ! empty ( $settings->meta_value ) && is_object( $query ) )
	{
		$key 	= $settings->meta_key;
		$value 	= $settings->meta_value;
		$args 	= $query->query;
		$args['meta_query'] = [
			[
				'key' 		=> $key,
				'value' 	=> $value,
				'compare' 	=> $settings->meta_compare
			]
		];

		$query = new WP_Query( $args );
	}

	return $query;
}, 90, 2);

Line no 3: Checking that user entered the key and value
Line no 5-16: If there have key and value, adding meta_query into existing query args and creating the new $query object.
Line no 19: Lastly returning the query object.

Here is the live Video: https://youtu.be/RKNIQ7nn2G0 . It will show how it is working.

Posted in