Display Your WordPress Recent Posts on a Static Page

This tutorial shows you how to display your recent posts on a static web page. So now you ask the question ‘Define Static?’ There are a variety of reasons why you may have static pages. If you have built a website from scratch and need a blog or news section. You want to pull some information from the blog to your homepage.

There have been several methods on the web including accessing the database. In this simple, but elegant solution I will show you 2 methods. One of which will be on a page with a .php extension and another will be on a page with a .htm extension.

If you want to display your latest posts on an existing WordPress blog please check out the following post.

Please check out Display your WordPress Recent Posts FAQs that I have set up to go along with this tutorial.

recent posts
Photo by Markus Winkler on Pexels.com

I have recently integrated a news blog into a static website for a charity project I volunteer for. The website was I have recently integrated a news blog into a static website for a charity project I volunteer for. The original website used custom PHP templates. It was only after the build process I added a WP news blog into it. It was easier integrating WordPress around the current design than changing everything. Anyhow the homepage is a static PHP page that fetches the data from a blog/news section which is in a sub-directory.

Prerequisites

I am assuming that you have WordPress installed on a PHP Web Server or are using web hosting. You will need a code editor. I recommend Visual Studio Code. I would recommend that you should have some basic knowledge of PHP, HTML and CSS.

Download

Get Started – Add Recent Posts

First of all, you need to open up your code editor and open the file in which you want to add your WP code snippet. At the top of the page you want to add the following:

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

 /*if you are getting 404 errors uncomment the next 2 lines*/
    //status_header(200);
    //nocache_headers();

?>

This loads the WP environment and template. If you have WP installed in a subdirectory then prefix wp-blog-header.php like so:

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

 /*if you are getting 404 errors uncomment the next 2 lines*/
    //status_header(200);
    //nocache_headers();
?>

Without this we wouldn’t be able to display our recent posts so please do not skip this step!

Now in the area, you want to display your recent posts insert the following

<?php   
$args = array( 'numberposts' => 6, 
               'post_status'=>"publish",
               'post_type'=>"post",
               'orderby'=>"post_date");

$postslist = get_posts( $args );
echo '<ul id="latest_posts">';
 foreach ($postslist as $post) :  setup_postdata($post); ?> 
    <li><strong><?php the_date(); ?></strong><br />
    <a href="<?php the_permalink(); ?>" title="<?php the_title();?>"> <?php the_title(); ?></a>
</li>
<?php endforeach; ?>
 </ul>

Line 2: The $args variable holds an array of items. In this case numberposts is the number of recent posts you want to display. Other arguments include post type, post status and order in which you want to display them. To view more options visit get_posts on the WP Codex.

Line 3: We get our posts and assign the array to a variable called $postslist

Line 5-10: We then start our foreach loop which will grab all the posts. We then wrap each post up in a div element. I have also included the date. The date will only display once there are many posts published on the same day. You can remove the date if not needed. We then display the posts pretty permalink underneath.

Adding to a Non PHP web page

Now to add our blog posts to a .htm or .html page. This requires a little hacking of our .htaccess file which should be in the root folder of your web server.


The htaccess file has a (.) as a prefix so it might not show. In your FTP software ensure that you can view hidden files. Furthermore, make sure you keep a backup to be on the safe side. You may also need to create one if you do not have one already.


In your .htaccess file add the following.

AddType application/x-httpd-php .htm

order allow,deny
deny from all

ErrorDocument 401 https://www.yoursite.com/error/401.html
ErrorDocument 403 https://www.yoursite.com/error/403.html
ErrorDocument 404 https://www.yoursite.com/error/404.html

Line 1 Make sure you use the correct extension. I have used (.htm) in this case but you could change it to (.html) etc:

Lines 6,7,8 Change the directory to which your error pages live. When the page is not available this will redirect to an error page.

Conclusion

I hope you have found this tutorial interesting. If you do have any problems then please contact me. You can also visit the Display your WordPress Recent Posts FAQs section that I have set up to go along with this post. I would also like to hear your success stories.

Topics:

290 replies on “Display Your WordPress Recent Posts on a Static Page”

  • Hi Tracy, Big thanks for this code, works a treat.

    2 questions please,

    1. does this have to be installed on same server as your wordpress blog? can you absolute ref the url and run this external?
    2. can you use this to adapt to display out full blog articles?

    Thanks ; )

    • Hi Frijj

      It does have to be installed on the same server unless someone else has tried it. I have an alternative method for displaying from different servers by parsing the RSS feed. Absolute URLS are allowed depending on server configuration but I don’t recommend it as it is a security risk.

      You can display the full article by adding the following above the foreach loop:

         
         global $more;
         $more = 1;
      

      then add the following inside the loop:

      <?php the_content();?>
      

      No need to wrap it in html tags as they are already in the content.

  • It is helpful. almost all what i need accept a thing in which i stuck. I want the posts in fade ticker. can u please help.

      • No, I dont know how to do this. I have some questions about this, is it possible to pay for a phone session on how to implement it? On some sites its working fine and others its not.

      • @Anthony. Have you used a WYSIWYG editor or manually coded your page? You need to open up test.php in a code view and at the top you should see a line which starts with

        You need to add the call blog-header above it like so:

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

        You also need to turn off PHP error display and log them to a file instead as displaying your errors to the public is a potential security risk. You can do this by opening wp-config.php and look for define(‘WP_DEBUG’, true);
        Change it to or add the following (if not there)

         // Enable WP_DEBUG mode
        define('WP_DEBUG', true);
        
        // Enable Debug logging to the /wp-content/debug.log file
        define('WP_DEBUG_LOG', true);
        
        // Disable display of errors and warnings 
        define('WP_DEBUG_DISPLAY', false);
        @ini_set('display_errors',0);
        

        If you get stuck I will be available over the weekend to help you out.

      • Hi, I’m working with this on Anthony, on certain sites we keep getting an error using this code and instructions you gave us that says “WordPress database error [Query was empty]”

        Can you please give us any clues as to what the issue may be…?

        Here’s one of the sites where we see it: http://longislandpowerwashingco.com

        It seems to come and go where the error displays and then doesn’t when you go to the site…

  • Brian McCallion
    Brian McCallion

    Tracy,

    I am confused!

    I have tried a few times to get this to work! Unfortunately, none have succeeded. I can’t figure out what I am doing wrong.

    I went to this site as I was frustrated as in my administration site my recent posts show, but when I access my site from my computer or another computer the recent posts don’t show. It is a static page on a wordpress.

    Can you assist me?

    Cheers!

    Brian

  • Hi and thanks for the post. It does work, however. Please clarify the positioning of the code on the pages. I interpreted when you say place it at the top of the page to mean on line 1 in the of the document. This does work but also generates 404 errors on the pages. Please check your site http://www.alfiemilne.org.uk/ inthe W3C link checker: http://validator.w3.org/checklink as it returns 404’s for some of your pages, even though the links are valid. I found this out when Google started reporting 404’s for some of my pages in Webmasters Tools. I have gotten round this by inserting the said code as part of the main code where I want the blog posts to appear. In my case in the footer of the pages. The code I have used is as follows and does not give 404 errors.

    • Hi Keith. The link to the blog header file needs to be before any html output otherwise you get a PHP error. I always place it above the doctype declaration. Thanks for pointing out the bug. The problem was my header template which linked to blog_header.php on all pages when it was only needed for the home page. All fixed now, thanks again!

      • Hi Tracy, Thanks for the reply. I understand what you’re saying, but I have the code right below this part of the page and I’m not getting any errors. I hope that helps?

      • The code to display the posts or pages can go anywhere in the body section. Just the link to blog_header should be above the Doctype. Is that what you are meaning? I had to remove the code as it wasn’t displaying properly. Feel free to add it again but wrap it in pre tags for easier reading.

      • No I have put all the code including the blog_header call in the footer.

        So all this is in the footer:

        3, ‘post_status’=>”publish”,’post_type’=>”post”,’orderby’=>”post_date”);
        $postslist = get_posts( $args );

        foreach ($postslist as $post) : setup_postdata($post); ?>

        <a href="” title=””>

      • Yep, I get you now. Some folk get errors when they place the call to blog_header within the body. Glad it worked for you eventually! Sorry about the code not displaying in the comment section. I will have a look to see if I can find the culprit!

      • I did use tagas but the code is still not displaying properly sorry. But I hope I have explained it without showing the code?

    • Hi Keith. Thanks for sharing your method. The Alfie Milne website has the link to blog-header above the doctype. I did notice a few 404 errors when I first wrote this post although I have checked through the link checker, Chrome Dev Tools and through an external app and only seen a couple of 404’s (1 of which is an external link) I guess it’s a case of trial and error. You can add
      status_header(200);
      directly underneath the call to blog-header to see if that makes a difference.

  • Tom Phillips
    Tom Phillips

    I used this technique to grab the 3 most recent posts from my clients “featured post” category and wrapped each post in its own div for prominent styling on the front page of the site. Worked like a charm and I’m sure I’ll be using this in the future. Clear concise write up and most of all extremely useful, cheers!

  • thank you, this worked great! the silly error i was making was putting this line: before the opening tag…

    great guide many thanks

  • Sorry but it did not work with me…
    it is not showing anything anything even my core php site is excluding the sidebar.php where these above mentioned codes are written…help…

  • GREAT !!!

    It works fine !
    I embeded your code in a html page (defined as php just before)
    and it runs magnifically.

    Great things are always free !!!

    Big thanks
    Bernard

  • Thanks for the code. It´s working, but I need the blogs only on a single page in an individual div container and not on all pages. Do you have an solutions for my problem?

    Thanks and best regards,
    tia

    • @Tia
      #Individual_div_problem
      Move div.events from (Line:6) to (Line:4)
      Move closing div from (Line:9) to (Line:11) or after the endforeach

      #single page problem
      You basically need to execute the snippet when on the correct page. You can fix this by using a simple IF statement before the snippet. You can filter pages, posts etc by name, ID and various other ways. Have a look at the following guide on the WP Codex

      http://codex.wordpress.org/Conditional_Tags

  • Thanks for the above. I do want to know if its possible to add the “Read More” feature into the integrated WordPress posts.

    The above tutorial shows how to integrate the full post. What I want is to limit the number of characters in the main page and have a Read More link to get to the full post.

      • Thanks. I have another problem.

        When I click “Continue Reading” it goes to a page with the theme of my wordpress theme. I want it to go to page having the same layout as my main page which contains that single post. Thanks.

      • The only way you can do that is to either design a WP theme with the same design. U could also split your design into templates, header,footer etc and include it from a WP theme. The latter could be a bit tedious!

      • This post helps to integrate a new blog into a current website. If the post is created in WP then it will link to that URL which will load your existing WP theme. Have you considered creating a WP theme the same style as your website?

    • Hi Turgs

      I can see you found a solution to your problem by looking at your website. Any chance you can share your solution.

      Thank you

      Addy

  • Stefan Lindgren
    Stefan Lindgren

    I couldnt get it to work in .html pages (Might be restrictions in my web hotel!?) however this workaround worked for me and might help others to.

    Step1: I created an .php file that I named ok.php (Use whatever name you like) and put it in the same directory where the .html file that you would like to display the posts on rests.

    The ok.php file looks like this:

    
    <?php require('../wp/wp-blog-header.php');?>
    
    <?php
        $args = array( 'numberposts' => 6, 'post_status'=>"publish",'post_type'=>"post",'orderby'=>"post_date");
        $postslist = get_posts( $args );
        foreach ($postslist as $post) : setup_postdata($post); ?>
           <div class="events">
                 <p><strong><?php the_date(); ?></strong></p>
               <p><a href="<?php the_permalink(); ? rel="nofollow">" title="<?php the_title(); ?>"><?php the_title(); ?><?php the_content(); ?></a></p>
          </div>
    <?php endforeach; ?>
    <code></pre>      
    
     <!--WP latest posts ends here -->
    
    Step2
    in your .html file put this code where you want the posts to show.
    <pre><code><!--#include virtual="ok.php" -->
  • Johanna Ouwerling
    Johanna Ouwerling

    Hi Tracy,
    Thanks for the code. Works like a charm!
    I have only one question. At the moment I get the thumbnails from the pictures, but I want the full picture to be displayed.
    Is that possible?
    I am using this code:

    10 );
    $lastposts = get_posts( $args );
    foreach($lastposts as $post) : setup_postdata($post); ?>
    <a href="”>

    Thanks!
    Johanna

    • U can change the size by specifying the following within the loop:

      <?php echo get_the_post_thumbnail($post->ID, 'full'); ?>
      

      Will display the full size of the image. You can change this for medium or large too

      Let me know how you get on?

      • Johanna Ouwerling
        Johanna Ouwerling

        Hi Tracy,
        That doesn’t do it. I still get the thumbnails.
        The original post has thumbnails.(Nextgen gallery) Maybe that has something to do with it?
        This is the code now:

        10 );
        $lastposts = get_posts( $args );
        foreach($lastposts as $post) : setup_postdata($post); ?>
        ID, ‘full’); ?>
        <a href="”>

        Johanna

      • Johanna Ouwerling
        Johanna Ouwerling

        Hi Tracy,
        Yes it is a Nextgen issue. When I disable NextGen I get to see the shortcode on the page. I will try and get an answer and maybe a solution at the NextGen forum.
        Thanks for all your help!
        Johanna

    • U need to add the following:

      'include'=>"1063,997,938,745"
      

      to this section

       
      $args = array( 'numberposts' => 4, 
                     'post_status'=>"publish",
                     'post_type'=>"post",
                     'orderby'=>"post_date");
      

      Where the numbers represent the Post IDs of the posts you want to display.
      As for the images you need to add post thumbnails to your posts then follow the instructions in this comment.
      http://www.worldoweb.co.uk/2012/display-your-wordpress-recent-posts-on-a-static-page#comment-1108

      Let me know how you get on

      • ‘4’,’post_type’ => ‘post’, ‘orderby’=>’post_date’,’order’=> ‘DESC’,’post_status’ => ‘publish’ ); $posts_array = get_posts( $args );

        foreach( $posts_array as $post ) : setup_postdata($post); ?>

        <a href="”>Read more

        <a href="”><?php
        //This must be in one loop

        if(has_post_thumbnail()) {
        the_post_thumbnail();
        } else {
        echo '’;
        }
        ?>

      • I am not sure what you are trying to achieve. Are you wanting 4 specific posts? Do you want to display the title or the excerpt of the post with read more or the full content? That code will not display anything. I suggest that you copy the code, from the post, to get it working first then then make small changes and refresh your browser to see if it works. If you wrap your code in ‘code’ Tags in the comment section it will read more easily.

        To add post thumbnails you need to add this in the loop.

        <?php echo get_the_post_thumbnail($post->ID, array(100,100), 'thumbnail'); ?>
        
      • i m send my code plz see mam where i m get mistake and plz how i add another code in my sendind code plzz tell me!!!!

Leave a Reply

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

This site uses Akismet to reduce spam. Learn how your comment data is processed.