WordPress get specific posts in arbitrary order

Right now, I'm doing:

$posts = get_posts(array('post_type' => 'page', 'post__in' => array(1, 3, 2, 9, 7)));

and am having two issues:

  1. Post 3 is of 'post_type' => 'post', so it doesn't get selected, but I want it! If I leave out 'post_type' => 'page', then only post 3 is selected (because it must assume 'post_type' => 'post'.).
  2. I want to be able to order the posts arbitrarily by their ids. If I knew how to use MySQL, I could do:

    SELECT * FROM wp_posts WHERE ID IN (1, 3, 2, 9, 7)
    ORDER BY FIND_IN_SET(ID, '1,3,2,9,7');

But, how should I do this with WordPress?


First fetch all posts arbitrarily by their ids and then loop through all the posts

You can do in this way:-

$posts=$wpdb->get_results("SELECT ID FROM $wpdb->posts WHERE ID IN (1, 3, 2, 9, 7)
ORDER BY FIND_IN_SET(ID, '1,3,2,9,7')");
for ($counter=0 ; $counter < $count; $counter++)
   $post=get_post( $posts[$counter]->ID, $output );
  //do your stuffs with posts

Hope this helps

Need Your Help

How to create a switch comparator in JS?

javascript jquery html css

is there a way to create a switch comparator like this one?

How do I access a MySQL database with Entity Framework

c# mysql entity-framework c#-4.0 ef-code-first

Background: I have already create a ASP.net MVC 4 app and a mysql database. I used code-first to generate the databases. The Web App is going to be used as the UI for interacting with the data. How...

About UNIX Resources Network

Original, collect and organize Developers related documents, information and materials, contains jQuery, Html, CSS, MySQL, .NET, ASP.NET, SQL, objective-c, iPhone, Ruby on Rails, C, SQL Server, Ruby, Arrays, Regex, ASP.NET MVC, WPF, XML, Ajax, DataBase, and so on.