WordPress Development Stack Exchange is a question and answer site for WordPress developers and administrators. Join them; it only takes a minute:

Sign up
Here's how it works:
  1. Anybody can ask a question
  2. Anybody can answer
  3. The best answers are voted up and rise to the top

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(
                   '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?

share|improve this question
up vote 1 down vote accepted

To restrict to letter X dynamically, the following should work. It depends upon the fact that WP_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 using SUBSTRING as you were trying to do, and one using LIKE. 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.

$args = array (
  'post_type' => 'post',
  'ignore_sticky_posts' => true,
  'substring_where' => 't',

function restrict_by_first_letter( $where, $qry ) {
  global $wpdb;
  $sub = $qry->get('substring_where');
  if (!empty($sub)) {
    $where .= $wpdb->prepare(
      " AND SUBSTRING( {$wpdb->posts}.post_title, 1, 1 ) = %s ",

//  $where .= $wpdb->prepare(
//    " AND {$wpdb->posts}.post_title LIKE %s ",
//    $sub.'%'
//  );
  return $where;
add_filter( 'posts_where' , 'restrict_by_first_letter', 1 , 2 );

$results = new WP_Query( $args );

var_dump($results->request); // debug
var_dump(wp_list_pluck($results->posts,'post_title')); // debug
share|improve this answer

You can use the posts_where filter to adjust theWHERE part of your query:

add_filter( 'posts_where' , 'custom_posts_where' );
$results = new WP_Query( $args );
remove_filter( 'posts_where' , 'custom_posts_where' );

function custom_posts_where( $where ){
    $where .= " AND SUBSTRING( post_title, 1, 1 ) ='z' ";
    return $where;
share|improve this answer

Your Answer


By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.