Sorting a Bricks Query Loop by Custom Field Matching the URL Parameter

A member asks:

I am looking to buy traffic from a source, and could make the process more dynamic if i could have the ads all be unique but draw from a page of listings that are created within a loop. Is it possible to make the 1st listing be pulled to the top spot by using a custom variable (text) in a subid or something similar? ie: domain.com/shop/?subid4=toaster-oven What i mean here is, subid4 is a text field assigned in metabox and the Custom post type is gifts… and there are 20 that load up in a listicle style post TIA!!

yes, that would be manually added when creating the campaign @ the traffic source!
so if niche was a skincare offer, subid8=neutrogena — and neutrogena if possible could be a field in the cpt?

This Pro tutorial shows how we can order a Bricks query loop to output the posts that have a specific custom field (subid) whose value is equal to the URL parameter (or query string) value.

Let’s consider this sample query loop at this URL: example.com/my-page/

These posts have a subid custom field and it is populated for some.

After implementing the tutorial when example.com/my-page/?subid=toaster-oven is visited:

Notice how the post having the subid custom field value of toaster-oven appears at the top.

and when example.com/my-page/?subid=neutrogena is visited, the post having the subid custom field value of neutrogena appears at the top:

Step 1

Edit a Page/template with Bricks and set up a query loop.

Do not set Order by and Order in the query settings.

Add the following in child theme‘s functions.php or a code snippets plugin:

// Register `subid` custom query variable.
add_filter( 'query_vars', function( $qvars ) {
	$qvars[] = 'subid';

	return $qvars;
});

// Function to check if the `subid` query variable is empty or not.
function bl_check_custom_query_var() {
	// get the value of the `subid` query var
	$subid = get_query_var( 'subid' );

	// return false if subid is empty
	if ( $subid === '' ) {
		return false;
	}

	return true;
}

add_filter( 'bricks/posts/query_vars', function( $query_vars, $settings, $element_id ) {
	if ( $element_id === 'yqupgi' && bl_check_custom_query_var() ) {
		// filter the posts by those having "subid" post meta = URL parameter value or those not having "subid" post meta set
		$query_vars['meta_query'] = [
			'relation' => 'OR',
			'subid_clause' => [
				'key' => 'subid',
				'value' => get_query_var( 'subid' ), // value of the `subid` query var
			],
			'no_subid_clause' => [
				'key' => 'subid',
				'compare' => 'NOT EXISTS',
			]
		];

		// order the posts by "subid" post meta (DESC) and by post date (DESC)
		$query_vars['orderby'] = [
			'subid_clause' => 'DESC',
			'post_date' => 'DESC',
		];
	}

	return $query_vars;
}, 10, 3 );

Replace yqupgi with the Bricks ID of the query loop-enabled element.