I have a query that pulls fields from the 3 most recent posts for a carousel:
get_posts('posts_per_page=3')
I need to re-order the results so that instead of it being
1, 2, 3
it is
3, 1, 2.
Any ideas on how to do this?
Reordering the way you want is really pretty trivial. Proof of concept:
$p = array(1,2,3);
var_dump($p);
array_push($p,array_shift($p));
var_dump($p);
With the WordPress code:
$p = get_posts('posts_per_page=3');
array_push($p,array_shift($p));
var_dump($p);
To make it more interesting, you can do the same with a filter. Since get_posts()
uses wp_query()
you can use the post_results
hook to reorder the results.
function post_shift_wpse_166761($p) {
remove_filter('posts_results','post_shift_wpse_166761');
array_push($p,array_shift($p));
return $p;
}
add_filter('posts_results','post_shift_wpse_166761');
$p = get_posts(
array(
'suppress_filters' => false,
'posts_per_page' => 3
)
);
var_dump(wp_list_pluck($p,'ID'));
Note that you also have to pass a suppress_filters
argument to get_posts()
.
I don't think WordPress offers any way to order posts as you like. It has ASC
and DESC
order to list posts.
But you can create a custom field for each carousel post to define carousel item orders. Let's say if you created custom field named carousel-order
and add numerical value to each post.
Then you can add custom order like this.
get_posts(
array(
'posts_per_page' => '3',
'meta_key' => 'carousel-order',
'orderby' => 'meta_value_num'
)
);
get_posts
returns an array, so you can dump it out in any order just using PHP.
Thanks for your ideas. I ended up creating two different queries for the carousel re-ordering using offset:
The first query displays the third most recent post:
$args = array( 'posts_per_page' => 1, 'offset'=> 2 );
$thirdPost = get_posts( $args );
and then spit the required fields into the first carousel slide div.
The next query grabs the first and second most recent posts:
$args2 = array( 'posts_per_page' => 2, 'offset'=> 0 );
$firstPosts = get_posts( $args2 );
and then using "for each" spits the required fields into the second and third carousel slide div.