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?
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.This is a trick.
Prepend to the letter you want to search a strange string:
Then apply a filter to
terms_clauses
hook:Finally use that function to remove the
%
preceding the strange string and the strange string itself:Untested.
I can’t comment on the previous answers, so I’ll add this note here in case anyone else faces this problem too:
The above wasn’t working for me, so I replaced:
with
as suggested here: https://stackoverflow.com/questions/47840519/listing-custom-taxonomy-terms-by-first-letter-using-name-like-does-not-work-ev
Based on gmazaap’s reply, I got this:
Tested with WordPress 5.2.2
Had to modify the regular str_replace with a preg_match because now WordPress seems to add something like a hash to protect SQL injections. Since this string seems to be random between queries the only solution is to use regex.