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:
<?php
$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.:*/
endwhile;
?>
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 :)
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:
<?php
$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.:*/
endwhile;
?>
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 :)
1 Answer
Reset to default 1At 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.