Display specific post on a WordPress page

I’m trying to get specific post to display in a single.php page, however for some reason I get all posts displayed. I’m not sure if I am getting post id correctly, but here is how I do it at the moment:

    <?php
    $post_id = (int) $_GET['p'];
    query_posts('p=' . $post_id);
    while(have_posts()) 
    { 
        $this_page = the_post();
        echo the_content();
    } 
    ?>

It should only display post with one id which is stored in $post_id variable, but for some reason it is getting all of them ;/

Related posts

Leave a Reply

3 comments

  1. not sure if this is what you are looking for, but I understand that you want to display a specific page on your single.php

    why not use this:

    <?php 
      $page_id = get_ID_by_slug('my_page_slug');
      $page_data = get_page( $page_id );
    ?> 
    
    <h2><?php echo $page_data->post_title; ?></h2>
    <p><?php echo $page_data->post_content; ?></p>    
    

    and add this to your functions.php

    /* get page by slug */

    function get_ID_by_slug($page_slug) {
      $page = get_page_by_path($page_slug);
      if ($page) {
        return $page->ID;
      } else {
        return null;
      }
    }
    
  2. Have you tried grabbing the post ID from the URL?

    <?php
       $post_id = (int) $_GET['p'];
       query_posts('p=' . $post_id);
    ?>
    

    Alternatively, this also might work:

    <?php get_post($post_id); ?>
    
  3. The ugly way:

    query_posts('p=11');
    

    (query_posts alters the main query)

    The less ugly way:

    $my_query = new WP_Query('p=11');
    while($my_query->have_posts()){
      $my_query->the_post();
      the_content();
    }