Salvatore Dibenedetto
Salvatore Dibenedetto

Reputation: 1043

Query post using post id

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

I am using this:

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

do stuff...

<?php endforeach;
 wp_reset_query(); ?>

This is returning an array with all post

Upvotes: 3

Views: 63301

Answers (5)

Mr Genesis
Mr Genesis

Reputation: 170

Change post_id= to p=.

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

Click in this link to see: Retrieve a Particular Post

Upvotes: 3

Jeremy
Jeremy

Reputation: 3809

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

Upvotes: 2

IcyNets
IcyNets

Reputation: 356

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. 

Upvotes: 2

user621639
user621639

Reputation:

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.

Upvotes: 5

Subhajit
Subhajit

Reputation: 1987

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

Upvotes: 0

Related Questions