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've a postmeta key saved in DB: mediSHOP_product_extras It's value is

Unserialized: Array ( [0] => Array ( [is_slider] => 0 [is_featured] => 0 [in_stock] => 0 [video_url] => [related_product_list] => ) )

For simplicity I didn't want to save each value as a new key/value combination in DB. But I might have made a mistake...

I want to use get_posts to fetch posts that have is_featured == 1 And I cannot figure out how to do this...

$slides_content = get_posts(array(
    'post_type'      => 'post',
    'posts_per_page' => 12,
    'meta_key'       => 'mediSHOP_product_extras',
    'meta_value'  => '1'
));

meta value needs to be 1, but it also needs to be is_featured == 1.

Simplest solution would be to just save is_featured as a separate key. But maybe you know how to solve my problem?

share|improve this question
    
A good rule of thumb to follow is: if you need to query by a meta key, don't store it serialized. –  helenhousandi Feb 5 '13 at 14:09
    
@helenhousandi I realized that, in fact I moved to using taxonomy for this... which is faster and better organized for this kind of tasks. –  Sandro Dzneladze Feb 5 '13 at 19:28

2 Answers 2

I think below code will work for you

$args = array(
   'post_type' => 'post',
   'meta_key' => 'mediSHOP_product_extras',
   'posts_per_page' => '12',
   'meta_query' => array(
       array(
           'key' => 'mediSHOP_product_extras',
           'value' => '1',
           'compare' => '=',
       )
   )
);
$query = new WP_Query($args);

if u face any problem let me know.
share|improve this answer
    
But, mediSHOP_product_extras = Array ( [0] => Array ( [is_slider] => 0 [is_featured] => 0 [in_stock] => 0 [video_url] => [related_product_list] => ) ) How will that query understand that I need to look at "is_featured" key inside mediSHOP_product_extras? –  Sandro Dzneladze Feb 5 '13 at 9:37

It is possible if you shape your meta query to look for the serialized string like this, assuming your array value is always an integer:

$params = array(
    'meta_query' => array(
        array(
            'key'     => 'mediSHOP_product_extras',
            'value'   => 's:11:"is_featured";i:1;',
            'compare' => 'LIKE'
        )
    )
);
$query = new \WP_Query( $params );

If the array value is a string or a boolean, the meta query value pattern should be altered:

// for string type values
's:11:"is_featured";s:1:"1";'

// for bool type values
's:11:"is_featured";b:1;'
share|improve this answer

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.