ma11hew28
ma11hew28

Reputation: 126417

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?

Upvotes: 0

Views: 851

Answers (3)

fregante
fregante

Reputation: 31728

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);

Upvotes: 0

ma11hew28
ma11hew28

Reputation: 126417

  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)));
    }
    

Upvotes: 0

Shakti Singh
Shakti Singh

Reputation: 86406

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

Upvotes: 1

Related Questions