Query post using post id

SSomeone can tell me what’s the best way to get a post using it’s id?

I’am using this:

Read More

$query = query_posts(‘post_id=’.$_GET[‘php_post_id’]);
global $post;
foreach ($query as $post):

do stuff…

This is returning an array with all post

Related posts

Leave a Reply

5 comments

  1. If you are looking to get a single post with an ID you already know or getting from another source, i’ll suggest the below code.

    $args = array(
            'post_type' => 'post',
            'post_status' => 'publish',
            'p' => $id,   // id of the post you want to query
        );
        $my_posts = new WP_Query($args);  
    
       if($my_posts->have_posts()) : 
    
            while ( $my_posts->have_posts() ) : $my_posts->the_post(); 
    
              get_template_part( 'template-parts/content', 'post' ); //Your Post Content comes here
    
            endwhile; //end the while loop
    
    endif; // end of the loop. 
    
  2. You can create a query like so:

      $rd_args = [
           'ID' => $postId
      ];
    
      $query = new WP_Query($rd_args);
    

    And then you can retrieve the post from the query. Or set it to the global query and loop over it:

    $GLOBALS['wp_query'] = $query;
    
    while ( have_posts() ) : the_post();
    
  3. Here is the code to fetch post using query_post if you know the ID.

    <?php
        $my_query = query_posts('post_id=111&post_type=parks'); // in place of 111 you need to give desired ID.
        global $post;
        foreach ($my_query as $post) {
           setup_postdata($post);
           the_title();
           the_content();
        }
    ?>