Support » Fixing WordPress » meta_query doesn't find value if custom field value is serialized

  • Have the following code:

    $args = array(
    	'meta_query' => array(
    		array(
    			'key' => 'my_meta_key',
    			'value' => $my_value,
    			'compare' => 'IN'
    		)
    	)
    );
    $posts = get_posts( $args );

    If my_meta_key is just a single value, this piece of code works perfectly, but when the my_meta_key is a custom field which have multiple values (so it’s stored as an serialized object), it won;t work anymore.

    As far as I can see this is expected behavior when I take a look to the code, but shouldn’t this just work? 🙂

    Or anyone solutions for this (without directly using a lot of SQL queries)?

Viewing 3 replies - 1 through 3 (of 3 total)
  • okay, figured this out:

    $args = array(
    	'meta_query' => array(
    		array(
    			'key' => 'my_meta_key',
    			'value' => '"' . $my_value . '"',
    			'compare' => 'LIKE'
    		)
    	)
    );
    $posts = get_posts( $args );

    Since the serialized string is like this: a:1:{i:0;s:1:"2";} it should always match, right? (of course when $my_value is 2 😉 )

    Smart or dirty?

    Can you not just serialize $my_value? Of am I oversimplifying the problem?

    Thanks for the suggestions.. that;s works too and may be even a better solution.. The only thing you’ve to keep in mind that you convert the values to string first before serializing (in case of integers, like ID’s).

    So this is it now (in my case):

    $args = array(
    	'meta_query' => array(
    		array(
    			'key' => 'my_meta_key',
    			'value' => serialize(strval($my_value)),
    			'compare' => 'LIKE'
    		)
    	)
    );
    $posts = get_posts( $args );

Viewing 3 replies - 1 through 3 (of 3 total)
  • The topic ‘meta_query doesn't find value if custom field value is serialized’ is closed to new replies.