0

I have a custom field where the value contains a comma separated list of items (like: test1,test2,test3), now I want to retrieve posts where the field contains one of the values, I have:

$query = get_posts( 
    array( 
        'post_type'      => 'custom_post', 
        'posts_per_page' => 11, 
        'meta_query'     => array(
            array(
                'key'     => '_my_custom_field_key',
                'value'   => array('test1'),
                'compare' => 'IN'
            )
        ) 
    ) 
);

And it fails. It works if I clear other values from the custom field so it only contains test1 but not when it's in the comma-separated group. In SQL I can use FIND_IN_SET function to search for the value, but I'm trying to reply on core WP as much as possible and avoid custom SQL codes, it would be cool if it were possible.

  • BTW here's a working SQL query: ` $query = $wpdb->get_col( "SELECT * FROM {$wpdb->postmeta} WHERE meta_key = '_my_custom_field_key' AND FIND_IN_SET( 'test1', meta_value ) > 0" ); ` – a378853 Aug 11 '14 at 0:28
  • Please add this extra information into the question, which should contain all the relevant information and it's easier to read, thanks. – birgire Aug 11 '14 at 0:49
2

Here are few ideas:

1) You could try to compare with LIKE instead:

'key'     => '_my_custom_field_key',              
'value'   => 'test1',                
'compare' => 'LIKE'

It should give you a SQL query with:

... LIKE '%test1%' ...

2) You might want to save the string as

,test1,test2,test3,

to make the whole word search easier:

'key'     => '_my_custom_field_key',              
'value'   => ',test1,',                
'compare' => 'LIKE'

3) Another option would be to save it to a meta key with multiple values.

4) You could also modify the generated SQL query via filters like posts_where and posts_clauses. Notice that get_posts() suppresses filters by default, but you can use the suppress_filters parameter to control it, or use WP_Query() instead.

5) Manually write the SQL query and fetch it with the $wpdb class, like you are doing already.

  • I'm not sure like is the best solution, if you query for test for example it will return all three values of test1, test2, test3 I think. – a378853 Aug 11 '14 at 0:28
  • @a378853 I added few more options that you might consider. – birgire Aug 11 '14 at 0:40

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.