0

I have a custom post type with its meta in an array. What I need to do is query based on the value of a key in that meta array.

$args = array(
    'post_type'         => 'my-cpt',
    'posts_per_page'    => -1,
    'orderby'           => 'meta_value',          // Sort by this value
    'meta_key'          => 'my_meta_array',       // Sort by this meta key
    'meta_query'        => array(
        array(
            'key'       => 'key here',            // WHAT GOES HERE?
            'value'     => array( 'meta-value' ),
        )
    )
);    

$query = new WP_Query( $args );

What goes in the meta_query key, if my key is my_meta_array[key]?

FYI: the keys are indexed by my_meta_array[key], stored in the db via update_post_meta( $post_id, 'river_helpers', 'my_meta_array' ), and retrieved via get_post_meta( $post->ID, 'my_meta_array', true );

3
  • If your value is stored in $my_meta_array['key'] then ... $my_meta_array['key']. That is just a PHP question not a WordPress one.
    – s_ha_dum
    May 12, 2013 at 1:22
  • Actually it's stored in meta as an array, i.e. $my_meta = get_post_meta( $post->ID, 'my_meta_array', true ); Then the keys are within the 'my_meta_array' key, i.e. my_meta_array[key] or $my_meta['key']. May 12, 2013 at 1:27
  • Ok. Got it. That is what you mean. Looks like you already have an answer.
    – s_ha_dum
    May 12, 2013 at 2:03

1 Answer 1

3

You can't do that. When you save postmeta (or any other meta, for that matter), WordPress runs it through maybe_serialize which turns objects and arrays into serialized data. When it gets pulled back out, it is run through maybe_unserialize.

Serialized data looks something like this:

a:1:{s:3:"one";s:3:"two";}

In other words, what get's stored cannot be queried in the way you want. The best you could do is a LIKE query, which will be unreliable at best and less performant. Just use LIKE as the compare argument of your meta query.

Your best bet: rethink how you store meta and move whatever key is to its own entry. Meta tables in WordPress are key value stores, it's not unreasonable to store multiple meta values per post type or plugin.

0

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

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