Take the 2-minute tour ×
WordPress Development Stack Exchange is a question and answer site for WordPress developers and administrators. It's 100% free, no registration required.

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 );

share|improve this question
    
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 '13 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']. –  Julie CodeRiver May 12 '13 at 1:27
    
Ok. Got it. That is what you mean. Looks like you already have an answer. –  s_ha_dum May 12 '13 at 2:03
add comment

1 Answer

up vote 3 down vote accepted

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.

share|improve this answer
    
Thanks for your help. –  Julie CodeRiver May 12 '13 at 2:03
add comment

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

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