2
votes

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

I'am using this:

$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

5

5 Answers

3
votes
get_post( $post_id, $output );

So in practice will look like:

$my_id = 7;
$post_id_7 = get_post($my_id);

Further reference about the post's parameters and fields, here: http://codex.wordpress.org/Function_Reference/get_post

Update: It's the best practice when you need to get a single post by id, no cicles required.

2
votes

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
votes

Change post_id= to p=.

$setQuery = 'p='.$_GET['php_post_id'];
query_posts($setQuery);

Click in this link to see: Retrieve a Particular Post

1
votes

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();
0
votes

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