Displaying WordPress latest post listings outside of WordPress

Something that comes up again and again for me is when clients ask about integrating the latest blog posts into some third party page. It may be that the homepage isn’t managed under WordPress, or some other software is running. Here are the 2 steps you can do to integrate a nice listing of the latest blog posts on other parts of your site.

There are, of course, 100 different ways to do this, this way uses the inbuilt functions of WordPress to run the SQL query.

Get access to WordPress functions

At the top of the page you will need to include wp-blog-header.php

<?php require('blog/wp-blog-header.php'); ?> 

Place this code at the very top of your page, before anything else runs. Note:Make sure the link to this file is correct, it may differ depending on where you’ve installed WordPress.

Blog post function

In your PHP code you will need to add a new function. This function takes parameters like how many posts you want to display, and what you want to pad the link with ($preitem & $postitem). It returns the fuction, rather than echoing it directly.

function DoTheBlogPosts($numberofposts,$preitem=" ",$postitem=" "){
  $args = array( 'numberposts' => $numberofposts, 'post_status'=>"publish",'post_type'=>"post",'orderby'=>"post_date");
  $postslist = get_posts( $args );
  $output = '';

 foreach ($postslist as $post) :  setup_postdata($post); 
 
    $output .= $preitem.'<a href="'. get_the_permalink($post) .'" title="' . get_the_title($post).'">'. get_the_title($post). '</a>' .$postitem.'
      ';
  endforeach;

return $output;
 }

Calling the function

In your PHP you can call the function like

DoTheBlogPosts(5)

to display 5 posts, without any formatting for a list

DoTheBlogPosts(4,"<li>","</li>")

to output the details with LI items before and after, just make sure that you open and close your list before & afterwards.

2 Comments

Leave a Reply

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