How can I change a value in an array?

WordPress Plugin Development: How can I retrieve posts that have a specific value of an array in a custom meta key?

  • I've created a custom post type with the slug my_post_type and several posts of that post type with a meta key of my_target_meta. The my_target_meta's value is an array looking like either of the followings. array( 'a' ) array( 'a', 'b' ) array( 'b', 'c' ) Now I'd like to retrieve the posts that have the element value of 'a' in the my_target_meta meta value. I tried the following but it does not work. $result = new WP_Query( array( 'post_type' => array( 'my_post_type' ), 'meta_query' => array( array( 'key' => 'my_target_meta', 'value' => array( 'a' ), 'compare' => 'IN', ) ) ) );

  • Answer:

    Never mind. This worked. 12$result = new WP_Query(             array...

Anonymous at Quora Visit the source

Was this solution helpful to you?

Other answers

Anonymous basically has it, but their query is likely to return too many results. Because that data is serialized you can’t select with with an equals or IN (MySQL doesn't know it's serialized data), you have to use a LIKE. Quoting the value you're searching for makes sure it doesn't match that as a substring of something else (e.g. a is part of all, ball, aardvark). i.e. http://www.simonbattersby.com/blog/2013/03/querying-wordpress-serialized-custom-post-data/

Nick Ciske

Nick Ciske alluded to quoting the value, and he's absolutely right.  It's worth putting it here explicitly. $result = new WP_Query( array( 'post_type' => array( 'my_post_type' ), 'meta_query' => array( array( 'key' => 'my_target_meta', 'value' => '"a"', 'compare' => 'LIKE', ) ) ) ); If you wanted to get really fancy you could put in the entire serialized chunk, like this: $result = new WP_Query( array( 'post_type' => array( 'my_post_type' ), 'meta_query' => array( array( 'key' => 'my_target_meta', 'value' => 's:1:"a"', 'compare' => 'LIKE', ) ) ) ); But, maybe that's overkill.

Trevor Mills

Just Added Q & A:

Find solution

For every problem there is a solution! Proved by Solucija.

  • Got an issue and looking for advice?

  • Ask Solucija to search every corner of the Web for help.

  • Get workable solutions and helpful tips in a moment.

Just ask Solucija about an issue you face and immediately get a list of ready solutions, answers and tips from other Internet users. We always provide the most suitable and complete answer to your question at the top, along with a few good alternatives below.