1

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?

2 Answers 2

1

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 ",
      $sub
    );

//  $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
2

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;
}

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

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