WordPress WP_Query with comma separated Strings

Viewed 862

I created a custom field with key 'director' for every post. One post has the value Joe Russo, another post Joe Russo, Anthony Russo. I'm trying to filter all posts by Joe Russo and want to find the titles of both posts. I want it to work for any name, given that they will always be separated by a comma. I tried the following:

$args = array(
            'meta_key'   => 'director',
            'meta_value' => 'Joe Russo',
            'compare' => 'LIKE',
        );

$meta_query = new WP_Meta_Query($args);
if($meta_query->have_posts()) {
    $titles = array();

    while($meta_query->have_posts()) {
        $meta_query->the_post();
        $titles[] =  get_the_title();
    }
    return $titles;
} else {
    return 'No posts found';
}

But that will only find the one with Joe Russo . I also fiddled with REGEXP as the compare method but couldn't get it working. Any ideas would be much appreciated!

1 Answers

As Johannes pointed out, I mistakenly used compare instead of meta_compare. This works fine:

$args = array(
            'meta_key'   => 'director',
            'meta_value' => 'Joe Russo',
            'meta_compare' => 'LIKE',
        );

Though I will probably replace this and use taxonomies instead, see comment from Xhynk.

Related