How can i get posts sorted out by meta_key from inner key array of post meta values, for more details please look at my code:

// Example output of each post_meta, key is views

    'all' => '334',
    'new' = '28',
    'old' => '280'

// wp_query with meta_query not working with above meta_key 

$popular = new WP_Query( array(
    'post_type'             => 'songs',
    'showposts'             => '20',
    'order'                 => 'DSC',
    'meta_key'              => 'views', // i want something like this views['all']
    'orderby'               => 'meta_value_num'
) );
  • I am about 99% sure that you can't do this with WP_Query because the data is serialized in the database ( automagically ). The solution would be to split them into their own post meta key value pairs than an array.
    – Howdy_McGee
    Dec 29, 2015 at 19:12
  • @Howdy_McGee is correct. WP_Query won't do this without a lot of help from filters but I'd sort in PHP if it were me. The complexity of the query you'd need is pretty high and I doubt the query would be efficient.
    – s_ha_dum
    Dec 29, 2015 at 19:18
  • @Howdy_McGee, s_ha_dum Thanks for ur comment, I feared from this, Is there any way to get all posts then with one foreach do sorting posts by that array first key ?! It is possible ?!
    – Behzad
    Dec 29, 2015 at 19:26
  • 1
    Never use serialized data if later you need to query individual data. That is why the database design decisions are so important early at the development stage. Better just save them as view_new, view_old and view_all. If you have existing data in the database. I will advice you to write code which (run once) go through each post and split the data into three individual meta.
    – Sisir
    Dec 29, 2015 at 19:33
  • 1
    This is not something you can add to meta_query. It is a limit at the database level. The database can't reliably manage serialized data, which is a PHP construct, not a MySQL one. It is just bad, bad, bad data design to shove multiple pieces of different information into the same key. It is a bit like making trailmix out of your information and expecting to be able to easily un-trailmix later.
    – s_ha_dum
    Dec 29, 2015 at 19:48


Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Browse other questions tagged or ask your own question.