get posts by id in wordpress

I want to get posts by id. Id’s are in array. I am using this code but now working.

$the_query = new WP_Query( array( 
    'post_type' => 'job_listing', 
    'post__in' => array( 311, 312 ) 
));

print_r($the_query); //this doesn't print any data

if ( $the_query->have_posts() ) {
    echo '<ul>';
    while ( $the_query->have_posts() ) {
        $the_query->the_post();
        echo '<li>' . get_the_title() . '</li>';
    }
    echo '</ul>';
}

Related posts

Leave a Reply

1 comment

  1. You can use get_posts() as it takes the same arguments as WP_Query.

    To pass it the IDs, use 'post__in' => array(311, 312) (only takes arrays).

    Below is the example.

    $args = array(
        'post_type' => 'job_listing',
        'post__in' => array(311, 312)
    );
    
    $posts = get_posts($args);
    
    foreach ($posts as $p) :
        //post!
    endforeach;