I filter my WP_Query
by this script:
$args = array (
'posts_per_page' => $posts_per_page,
'post_type' => $post_type,
'meta_key' => 'post_views_count',
'orderby' => 'meta_value_num',
'showposts' => 160,
'order' => 'DESC',
'paged' => $paged,
'tax_query' => array(
array(
'taxonomy' => $term->taxonomy,
'field' => 'slug',
'terms' => $term->name)));
And I would like to add the filter SUBSTRING(post_title, 1,1) ='z'
.
Is that possible to implement it?
what’s the best practice to loop only post which start with letter X?
To restrict to letter
X
dynamically, the following should work. It depends upon the fact thatWP_Query
will let ad hoc parameters pass through. That lets you send your own data to the filters. I do not know if this is intentional behavior so caveat emptor, but it is very useful behavior.Simply send your letter of choice via the
substring_where
parameter and let the filters work. There are two versions, one usingSUBSTRING
as you were trying to do, and one usingLIKE
. I don’t know which is faster, though they seem very close.I also used
$wpdb->prepare
but that may not be necessary. It depends on where you data is coming from.You can use the
posts_where
filter to adjust theWHERE
part of your query: