To achieve this, you can start by implementing the solution for this question. That will allow you to filter posts by their first letter (no custom meta required):
Assuming
starts_with
is the name of the argument we want to use, we
can filterposts_where
to add aWHERE
clause limiting results to
those that begin with the given value ifstarts_with
has been set on
the query:function wpse_298888_posts_where( $where, $query ) { global $wpdb; $starts_with = $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 );
With this filter added, we can query posts like this:
$query = new WP_Query( array( 'starts_with' => 'M', ) );
That will return all posts beginning with “M”.
To support filtering the post type archive this way via the URL, you just need to register starts_with
as a query var:
function wpse_346729_query_vars( $query_vars ) {
$query_vars[] = 'starts_with';
return $query_vars;
}
add_filter( 'query_vars', 'wpse_346729_query_vars' );
Doing this means that if the starts_with
parameter is passed via the URL, it will be set on the main query, which will cause our posts_where
filter to be applied to the current main query.
http://example.com/?post_type=staff&starts_with=A