How to get posts using WordPress API

In this tutorial we are going to show you how to use WordPress API to get posts data. If You don’t have a WordPress Environment installed check out our video where we show how to quickly get WordPress Development Environment up and running. Tutorial is available here.

To test our sample code we are going to use a plugin which allows executing PHP code on our site.

Installing PHP code plugin

  1. Log in to your WordPress site.
  2. Navigate to Plugins
  3. Click Add New button
  4. In the search field enter ‘php’
  5. Pick one of the plugins and install it by clicking Install Now
  6. Navigate to Plugins and activate newly installed plugin by clicking Activate link
  7. Go to Appearance and Widgets
  8. Add plugins widget to your site

You will write our sample code in the widgets body.

We are using “Executable PHP widget” which can be found here http://wordpress.org/extend/plugins/php-code-widget/

Code snippets

To get recent posts write following code which lists posts titles in a form of clickable links.

<?php
// Get recent posts
$posts = get_posts();
// Iterate throught the results
foreach ($posts as $post) {
   // Get post title
   $post_title = $post->post_title;
   // Get post url
   $post_url = get_permalink($post->post_ID);
   echo '<div>';
   // Construct post URL
   echo '<a href="'.$post_url.'">'.$post_title.'</a>';
   echo '</div>';
}
?>

Getting recent posts from category is very easy. You need to provide category_name with one of your category slugs. Get posts from category code looks like this.

<?php
$posts = get_posts('category_name=wordpress');
foreach ($posts as $post) {
   $post_title = $post->post_title;
   $post_url = get_permalink($post->post_ID);
   echo '<div>';
   echo '<a href="'.$post_url.'">'.$post_title.'</a>';
   echo '</div>';
}
?>

Reference

http://codex.wordpress.org/Template_Tags/get_posts

Leave a Reply

Want to join the discussion?
Feel free to contribute!

Leave a Reply

Your email address will not be published. Required fields are marked *


*

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>