Skip to content

Instantly share code, notes, and snippets.

@nmec
Created September 7, 2012 08:27
Show Gist options
  • Save nmec/3664336 to your computer and use it in GitHub Desktop.
Save nmec/3664336 to your computer and use it in GitHub Desktop.
Sorting a WordPress loop by post__in
<?php
$posts = array(5, 2, 43, 12);
// Get the posts
$my_loop = new WP_Query(array(
'post__in' => $posts,
'post_type' => 'any',
'posts_per_page' => -1,
));
// Re order the posts
$reorder_loop = array();
foreach($posts as $rpid)
foreach($my_loop->posts as $index => $fpid)
if($fpid->ID === $rpid) $reorder_loop[] = $my_loop->posts[$index];
$my_loop->posts = $reorder_loop;
// Start the loop
if ($my_loop->have_posts()) : while ($my_loop->have_posts()) : $my_loop->the_post();
the_title();
the_content();
endwhile; endif;
<?php
$posts = array(5, 2, 43, 12);
// Get the posts
$my_loop = new WP_Query(array(
'post__in' => $posts,
'post_type' => 'any',
'posts_per_page' => -1,
'orderby' => 'post__in'
));
// Start the loop
if ($my_loop->have_posts()) : while ($my_loop->have_posts()) : $my_loop->the_post();
the_title();
the_content();
endwhile; endif;
@sarveshacharya
Copy link

This way sticky posts get appended automatically. After using
$my_loop = new WP_Query(array( 'post__in' => $posts, 'post_type' => 'any', 'posts_per_page' => -1, 'orderby' => 'post__in', 'ignore_sticky_posts' => 1 ));
Then 'orderby' => 'post__in' doesn't work. Any solution for this?

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment