Ever needed to display content in your wordpress template from a specific post, page or custom post type? Read on to see how easy it is to get post or page content by id in WordPress with just a few lines of code.
This process will work with wordpress posts, pages or custom post types, but for the rest of this tutorial I am going to use the term “post”.
Get Post id
The first thing you must do is find the id of your wordpress post. There are a few ways to do this:
- In your WordPress admin Click on the Posts menu to view a list of posts. Click on the desired post to edit it. When the post opens for editing you will see the post id in the browser address bar.
- Follow the same process as above but just hover over the desired post instead of clicking on it and you will see the page id in the status bar.
- Install a free wordpress plugin such as this one: Admin Post Listing Ids, which shows the post id beside each post in the admin listing
After installing this plugin the id of each post will be visible when viewing the list of posts in your wordpress admin
Get post content by id
Ok, we’re nearly there. Now you need to add the following code to your page template. If you don’t know how to edit a page template this handy wordpress page template tutorial will help.
Open your page template and add the following code to the section where you want to display the post content.
<?php $page_id = 6; // Enter your post, page or custom post type id here $page_data = get_page( $page_id ); //gets all page data $content = apply_filters('the_content', $page_data->post_content); //filters just the post content $title = $page_data->post_title; // Get title echo '<h2>' . $title . '</h2>'; //output title in heading echo $content; // Output Content ?>
Other output options:
In the above example we output the title and content. There are other options available. The following example outputs the title, and excerpt and a link to “Read More”.
<?php $page_id = 6; // Enter your post, page or custom post type id here $page_data = get_page( $page_id ); //gets all page data $excerpt = apply_filters('the_excerpt', $page_data->post_content); //filters just the excerpt $title = $page_data->post_title; // Get title $permalink = get_permalink($page_id); //get the permalink echo '<h2>' . $title . '</h2>'; //output title in heading echo $excerpt . '<br/>'; // Output excerpt echo '<a href="' . $permalink . '">Read more</a>'; //Permalink to full post/page ?>