WordPress Tricks

Query or show a specific post in wordpress

PHP Code Example to Query a WordPress Post

Example 1

The following code will Query the post with post id 26 and Show the title and the content.

$post_id = 26;
$queried_post = get_post($post_id);
$title = $queried_post->post_title;
echo $title;
echo $queried_post->post_content;

Example 2

The following style could be more useful as it lets the user customise the font easily.

$post_id = 26;
$queried_post = get_post($post_id);
<h2><?php echo $queried_post->post_title; ?></h2>
<?php echo $queried_post->post_content; ?>

Example 3

Using an Array… The following code will query every post number in ‘thePostIdArray’ and show the title of those posts.

<?php $thePostIdArray = array("28","74", "82", "92"); ?>
<?php $limit = 4 ?>
<?php if (have_posts()) : ?>
<?php while (have_posts()) : the_post(); $counter++; ?>
<?php if ( $counter < $limit + 1 ): ?>
<div id="post-<?php the_ID(); ?>">
<?php $post_id = $thePostIdArray[$counter-1]; ?>
<?php $queried_post = get_post($post_id); ?>
<h2><?php echo $queried_post->post_title; ?></h2>
<?php endif; ?>
<?php endwhile; ?>
<?php endif; ?>


About the author

Janaki(http://mjanaki.com) - A Software developer with 9+ years of experience in multiple technology projects across web, mobile, and cloud applications with expertise in PHP, C#, MySQL, Web services and open source platforms.

Similar Posts

WordPress Get Page Content By Page Id
Query X Number of Recent Posts

Comments are closed.