0

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?

1

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().

0

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'
    )
);
  • Thanks - the trick is that the posts will be changing daily so 1 = most recent post 2 = second most recent post 3 = third most recent post and I need to switch order so that it displays as: 2 = second most recent post 3 = third most recent post 1 = most recent post It would be cumbersome for the editors to keep updating the post order manually - so trying to find solution either using PHP or jQuery most likely. – hml Oct 28 '14 at 21:36
  • get_posts returns an array, so you can dump it out in any order just using PHP. – Wyck Oct 28 '14 at 23:03
0

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.

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.