get_terms – name__like a number

Using Get Terms with the argument of ‘name__like’, how do i return all results that start with any number?

I’ve tried:

Read More
$feats = get_terms( 'movies', array('name__like' => '1', 'name__like' => '2', 'name__like' => '3' ) ); 

and

$feats = get_terms( 'movies', array('name__like' => '1,2,3,4,5,6,') ); 

Neither work properly. The first method will return the last “name__like” value but ignore the rest.

Any ideas?

Related posts

Leave a Reply

1 comment

  1. Looking at the get_terms function definition, the value for name__like will be passed to the SQL query like:

    " AND t.name LIKE '{$name__like}%'"
    

    As such, I believe that you can only search for one of the numbers.

    As an alternative strategy, you could iterate over the numbers you want to pull from the database:

    $terms = array();
    $numbers = range( 1, 6 );
    foreach ( $numbers as $number )
        $terms[] = get_terms( 'movies', array( 'name__like' => $number ) );
    

    As yet another alternative, you could make all of these terms that you want to get a child of another term. For instance, if you make a parent term called “Numbers”, with id of 5, and assign all of the “numbered” terms as a child of this term, you could do:

    get_terms( 'movies', array( 'parent' => 5 ) );
    

    Obviously, the success of either strategy is dependent upon your use case. The first alternative is rather expensive, but with a nice caching strategy really shouldn’t be an issue. The second method requires structuring data differently that may or may not work for your situation.