How can I have wordpress print posts whose IDs appear in an array?

I have an array of post IDs contained in $postarray. I would like to print the posts corresponding to these IDs in WordPress.
The code I am using is as follows:

query_posts(array('post__in' => $postarray));
if (have_posts()) :
    while (have_posts()) : the_post();
        the_title();
        the_excerpt();
    endwhile;
endif;

Despite this, the loop prints the most recent posts and not the posts contained in the array. How can I have wordpress utilize the post IDs I supply in the array and print those posts in order?

Related posts

Leave a Reply

1 comment

  1. You may have to break out of the standard WP Loop for this…

    Try and use the get_post() function which takes the ID of a post and returns an object containing a the details of the post in the usual OBJECT or Associate or Numeric Array format.

    See full-explanation of get_post().

    You can come up with a custom routine to parse each item in the array. Here’s a brief example:

    function get_posts_by_ids( $postarray = null ) {
        if( is_array( $postarray ) )
            foreach( $postarray as $post ) {
                $post_details = get_post( $post[0] );
    
                // Title
                echo $post_details->post_title;
                //Body
                echo $post_details->post_content ;
            }
    }
    

    Hope this helps 🙂