is there a possibility of filtering posts by terms using regexp? My code doesn't quite seem to work.

$tax[] = [
    'taxonomy'  => 'tax_name',
    'field'     => 'name',
    'terms'     => $name,
    'operator'  => 'REGEXP',

The $tax variable is then properly added to WP_Query args.

  • I don't get your question here, why do you need to match taxonomy names with regex – Pieter Goosen Jul 20 '16 at 8:24
  • I'm doing a custom search and I need to match the post taxonomy with user input with regex. – Pavel Koch Jul 20 '16 at 8:33
  • Are you talking about taxonomies or terms here. Please read this first – Pieter Goosen Jul 20 '16 at 8:55

This is untested, but give it a go. First get a list of the term names in the taxonomy. Then filter the returned array of names against your regex. Then use that filtered array of names for your WP query.

// assumes these assignments:
// $taxonomy - the taxonomy name you are querying against
// $regex - the regex to match the term names against

// First get all the terms that have posts:

$terms = get_terms( array(
    'taxonomy' => $taxonomy,
    'fields' => 'names', // return an array of term names
) );

$filtered_terms = preg_grep($regex, $terms);

// when you use this, expand $args with other relevant arguments for your query, such as post type:

$args = array(
    'tax_query' => array(
            'taxonomy' => $taxonomy,
            'field'    => 'name',
            'terms'    => $filtered_terms,

$the_query = new WP_Query( $args );

// Then run your loop

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

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