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 626 Bricks code tutorials with BricksLabs Pro

Leave the first comment

 

Related Tutorials..

Filtering Breadcrumbs in Bricks

Filtering Breadcrumbs in Bricks

Using the bricks/breadcrumbs/items filter to modify Bricks' breadcrumbs’ element programmatically.
Categories:
How to Exclude Elements from Bricks Editor

How to Exclude Elements from Bricks Editor

Bricks has a handy bricks/builder/elements filter using which the available elements that show up after clicking + (or ⌃/⌘ + ⇧ + E) in the…
Categories:
Tags:
Pro
Display 3 Category-related Posts and Supplement with the Latest Published Posts if Necessary

Display 3 Category-related Posts and Supplement with the Latest Published Posts if Necessary

In the Bricks Facebook group a user asks: Show latest 3 related posts based on category and IF THERE ARE NOT ENOUGH, fill the empty…
Filtering out Media Items from “Select post/page” Bricks control

Filtering out Media Items from “Select post/page” Bricks control

The dropdown that appears after choosing "Internal post/page" when setting a link in Bricks shows media (attachment) items besides Pages, Posts and other CPTs. If…
How to Remove Name and Website Fields in Bricks Comment Forms

How to Remove Name and Website Fields in Bricks Comment Forms

Updated on 14 Mar 2024 In the BricksLabs Facebook group a user asked: What is the best method to remove fields from the Bricks "Comments"…