is it possible to sort posts inside a query based on post value that is in an array - but using the last element of the array?

The code looks something like:


$mostsharedposts= new WP_Query( 
        array( 'posts_per_page' => 10,
               'meta_key' => 'mashsb_shares',
               'orderby' => 'meta_value', 
               'order' => 'DESC' ) );

while ( $mostsharedposts->have_posts() ) : $mostsharedposts->the_post();

/* Loop here e.g.:*/


meta_value is an array, and I just need the last element of that array. Can I somehow extract that element in a variable, using explode() and end() and sort by that variable or ...? Any idea would be helpful :)


At the stage of retrieving posts from database this is impossible (or at least impractical), since arrays are stored serialized by PHP in meta table and SQL won't be able to process them on the fly effectively.

This is easy enough to do for specific set of posts retrieved, just sort results in $mostsharedposts->posts before output. But that won't give you sane continuous pagination in that order.

In a nutshell if you want this in reliable non–hacky way, you will likely want to break out copy of that value in array into separate meta field.

  • If I understood you correctly, this can be done, but the pagination won't work? The (bulletproof) working solution would be to modify the plugin so it stores (copies) the last value of the array into a new meta field? Thanks for the help, btw :) – idjuradj Oct 11 '14 at 14:43
  • @Nicholas you can retrieve some X posts and sort them after retrieval, but it doesn't mean posts on next/previous page would be sorted properly. This doesn't matter if you only have one list/page, but it does for pagination. – Rarst Oct 11 '14 at 14:52

Your Answer

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

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