Term begins with a letter

I had a template that relied on

$terms = get_terms( "ingredient", array( 'name__like' => $letter ) );

to return all posts where the custom taxonomy ingredient begins with $letter.

The behaviour of name__like was changed in WP 3.7 to a text search instead of beginning.

What function can I use to achieve the results I had before? Do I need a custom query?

4 Answers
4

You will need to filter the query, which you can do with the terms_clauses hook. This is very similar to G-M’s solution but does not require a prefix on your search string.

function old_style_name_like_wpse_123298($clauses) {
  remove_filter('term_clauses','old_style_name_like_wpse_123298');
  $pattern = '|(name LIKE )\'%(.+%)\'|';
  $clauses['where'] = preg_replace($pattern,'$1 \'$2\'',$clauses['where']);
  return $clauses;
}
add_filter('terms_clauses','old_style_name_like_wpse_123298');
// $letter="str"; // test
$terms = get_terms( "ingredient", array( 'name__like' => $letter ) )

Leave a Comment