23rd Mar '23
/
0 comments

Querying for Posts Starting with a Specific Letter in Bricks

Looking to show all posts that begin with a letter, like say A in Bricks?

Set Posts per page to a number that is larger than the total number of posts. Ex.: If there are 100 published posts, set Posts per page to say 200 (a realistic number of max no. of posts that will ever be published).

Then add this in child theme‘s functions.php or a code snippets plugin:

function wpse_298888_posts_where( $where, $query ) {
	global $wpdb;

	$starts_with = esc_sql( $query->get( 'starts_with' ) );

	if ( $starts_with ) {
		$where .= " AND $wpdb->posts.post_title LIKE '$starts_with%'";
	}

	return $where;
}
add_filter( 'posts_where', 'wpse_298888_posts_where', 10, 2 );

add_filter( 'bricks/posts/query_vars', function( $query_vars, $settings, $element_id ) {
	if ( $element_id === 'lgbeyi' ) {
		$query_vars['starts_with'] = 'A';
	}
	
	return $query_vars;
}, 10, 3 );

Replace lgbeyi with the Bricks ID of your Query Loop enabled or Posts element.

Reference

https://wordpress.stackexchange.com/a/298913/14380

Get access to all 633 Bricks code tutorials with BricksLabs Pro

Leave the first comment

 

Related Tutorials..

Pro
Posts Grouped by Authors in Bricks

Posts Grouped by Authors in Bricks

This Pro tutorial for Bricks users provides the steps to loop through users and inside that, through posts whilst setting the inner query's author parameter…
Pro
How to move data attributes from outer element to nested element in Bricks

How to move data attributes from outer element to nested element in Bricks

Consider a scenario where a Container/Block in Bricks is made up of image on the left side and a heading with text blurb on the…
Pro
“Truncate text to these many characters” Bricks Control

“Truncate text to these many characters” Bricks Control

Bricks provides a :<number> dynamic data tag modifier that can be used to limit the amount of text by the specified number of words. Ex.:…
Pro
Previous Two Posts in Bricks Query Loop

Previous Two Posts in Bricks Query Loop

This Pro tutorial shows how we can modify the parameters of a Bricks query to limit the posts to the previous two whilst cycling to…