0

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?

Community
  • 1
  • 1
ma11hew28
  • 121,420
  • 116
  • 450
  • 651

3 Answers3

1

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')");
$count=count($posts);
for ($counter=0 ; $counter < $count; $counter++)
{
   $post=get_post( $posts[$counter]->ID, $output );
  //do your stuffs with posts
}

Hope this helps

Shakti Singh
  • 84,385
  • 21
  • 134
  • 153
  • This would work, but I think you're doing excessive SQL queries. AFAIK, `get_post` does an SQL query. So, you could just replace the first line with `$order => array(1, 3, 2, 9, 7)`. But then you'd still be doing five SQL queries, one for each post, Also, `foreach` is faster & cleaner in this & most cases. See this [answer](http://stackoverflow.com/questions/4329800/wordpress-get-specific-posts-in-arbitrary-order/4337226#4337226). – ma11hew28 Dec 02 '10 at 16:31
0
  1. Kawauso on the #wordpress IRC channel informed me that "post_type takes an array of values." From that, I found that the following also selects post 3:

  2. So, I did the following:

    $post_ids = array(1 => 0, 3 => 1, 2 => 2, 9 => 3, 7 => 4);
    $posts = get_posts(array('post_type' => array('post', 'page'),
                             'post__in' => array_keys($post_ids)));
    $ordered_posts = array(0,0,0,0,0); // size of five; keeps order
    foreach ($posts as $p) {
      setup_postdata($p);
      $ordered_posts[$post_ids[$p->ID]] = array(
        'permalink' => get_permalink($p->ID),
        'title' => $p->post_title,
        'excerpt' => get_the_excerpt(),
        'date' => date('F j, Y', strtotime($p->post_date)));
    }
    
ma11hew28
  • 121,420
  • 116
  • 450
  • 651
0

According to this thread, you can use this code and then use the classic WordPress loop:

$args = array(  
'post_type'=>'page',  
    'orderby'=>'menu_order',  
    'order'=>'ASC'  
);  
query_posts($args);
fregante
  • 29,050
  • 14
  • 119
  • 159
  • This is good to know, but in this case, they are not all pages, and I think they're in a different order than menu order. – ma11hew28 Dec 02 '10 at 19:29