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”

  • Jasminkumar Patel
    Jasminkumar Patel

    Your code work great for one worpress blog, but what if i want to add two different blog posts in one php page, than i need two times

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

    and second time it shows same data of first blog

    • Hi Parvi. Have you followed the tutorial? If so which bit are you stuck with? If your HTML page ends in .html, .htm etc then you need to add the .htaccess snippet alternatively change the extension to .php which you could also hide in your .htaccess

  • Hi Tracy,

    I really like the format of your wordpress posts (ie date, posted by, comments). Also, with the number of pages at the bottom.

    Would you mind sharing your code for this? I like the simplicity of your blog.

    Thank you!

  • Hi Tracy,

    Thanks so much for this. but say i already had a wordpress.com blog, not a self-hosted one, i wanted to use with the static page…is it at all possible to do similar things with that blog?

    Also, is it possible to open blogposts within the page? for example, to make it so that when a user clicks on a post displayed in the recent posts sidebar, that post opens within a div on the same page?

    Am i reaching too high? hahaha…thanks

    • Unfortunately you don’t have much control with the layout of your WP.com website unless there are any paid addons/themes that help. I switched to self hosting in 2008 to have more control.

      If you had your own web site (Non WP) your best bet for a wordpress.com blog would be to fetch the RSS feed. This could probably be fetched asynchronously and placed in a div on your current website with Javascript, or saved in a database.

  • Hey Tracy,

    great article,

    but I am having problem implementing it to my static page. I have Multilingual (Polish and English) WP blog. It is very simple because I need only CMS for making posts.
    I have in my root folder named “blog” which has WP.
    To index.php in root I added at the top + the rest of your code in the part I wish to see my posts, but as a result I get nothing of posts.
    Also can you tell me how to attach pagination to my static page for this blog posts. Do I do it in WP as admin or I can do it in my static page.

    * Link to static page is http://bojanarcon.com/ihif/ .
    * Link to blog in Polish is http://bojanarcon.com/ihif/blog/?lang=pl. I guess it has to do something with url but because I don’t know PHP I have no idea how to fix the problem.

      • Lawrence
        Lawrence

        Ok, lets say that default is in English: mysite.com/blog – for this I use “require( ‘blog/wp-blog-header.php’ );”
        But, what about french version: mysite.com/blog/fr/ ? How to display my WordPress recent french Posts on my static french page?

      • Lawrence
        Lawrence

        I found the solution, it’s simple:

        $args = array( ‘numberposts’ => 1, ‘post_status’=>”publish”, ‘lang’ => ‘fr’, ‘post_type’=>”post”, ‘orderby’=>”post_date”);

        That works well

  • Hi, somehow I don’t get this thing and I hope I am not to stupid. If I place the code snipet in my functions.php I end with a white page. Do you have any recomandations where to place the code snippets ?
    tks in advance

      • Hello Tracy,

        First, great article, I’ve successfully used it on a couple non-WP websites. However, on one of these websites hosted by justhost.com (cPanel shared hosting using NGINX), a get the “white screen”. There is no whitespace directly before the php opening tags and after the closing php tags in my functions.php Do you have any idea why this is not working? Here’s my test page: http://www.azempiredoors.com/test.php Do you think its because this hosting uses NGINX..HTTP server and reverse proxy?

        Any help is appreciated. Thank you in advance.

      • Hi John
        White screen errors are internal server errors and can be caused by many issues including typos, memory limit, themes & plugins etc.
        Can you add the following above the doctype in test.php?

        <?php
        require('wp-blog-header.php'); //your path to the file
         status_header(200);
         nocache_headers();
        ?>>
        

        If that still doesn’t work can you look in your error logs?

      • Hello Tracy,
        I had actually already added the above code above the doctype but still white screen. It must have something to do with this particular host, because I ran the exact same code on two other hosts (Godaddy and Hostway) and it runs perfectly.

        I’m stumped.

      • Here’s the error log:

        [29-Aug-2017 09:25:55] PHP Fatal error: require() [function.require]: Failed opening required ‘/blog/wp-blog-header.php’ (include_path=’.:/usr/lib64/php:/usr/share/pear’) in /home/azemp/public_html/test.php on line 1

      • Looks like it cannot find the wp-blog-header.php. If your test file is in the root folder then is your path to wp-blog-header.php would be

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

        Is that correct?

      • The test.php file is in the root directory. However, the actually WP installation is in a subdirectory named blog. That is why I used /blog/wp-blog-header.php
        Is this not correct?

      • Sub directory is not a sub domain. No, the forward slash is not in the actual code for the php require path…I accidentally added it to my last post. Here is the actual code I’m using in the test.php file:

      • I have contacted our host…they are so lame…seriously. So, we’ve decided to move to a different host. The link that you sent to that blog post is likely the issue that we are experiencing but on a shared hosting environment, we are not able to access those two fastcgi files mentioned in that post.
        Thank you for all of your effort…much appreciated!

    • Hi, Tracy,
      tks for your reply.
      I copy the code from above into gedit, to secure that there is no garbage in the code. I played around with the path’s for the last hour or so. The result is allways the same – white screen. It looks like it is a very basic problem. No clue. The blog I am working on is a future project of mine, if I cant get it to work no worries.
      tks

      kosta

      • If I remember rightly I had a problem using Gedit in the past automatically adding whitespace to files before uploading. Have you checked with another text editor or IDE? Are you getting any PHP errors?

  • One of the most useful codes I’ve tried yet however…
    I still cannot see the whole post only the title …like the one i have on the sidebar….ie its pulling sidebar info …not the posts… I want it to look like the posts in a facebook like box

      • Tracy..thankyou for your time..much apreciated. I used the code and works a charm…thanks to the comments on the script. ..the only thing I forgot first was to re add the bit in the top

        (‘YourSubDirectory/wp-blog-header.php’)
        as I was playing with other scripts to try and get it to work.
        Being a real newby to wordpress (6 days old) and only recently got into php linking ( all other stuff has been xhtml) the whole thing was a bit of a headache…learning how to call this file and that file. Thank you for your help I really apreciate it
        I have found another code that worked as well but least with yours I now understand what I’m coding. ….the other code case you interested …..>>>>

        http://www.fox-enterprise.com/wordpress

        again you can see I’ve used the_content as I wanted to see the full post but with your script I now have the option of scaling ie
        the_excerpt for snippets
        Again thank you for your time It’s great to get help….x

      • Dont know if you got my last reply as i had to edit it then it dissapeared ???
        Thanks for your help.. with your code I can understand what I’m doing being only 6 days old with wordpress. I found another code you can see @
        http://www.fox-enterprise.com/wordpress
        theirs is slightly different but now I get the idea of what I’m doing.Again many thanks…and if the last reply comes through just ignore this one..x

  • Hi there. I am running a small board based on phpBB for my local boardgame / roleplaying group and would like to add a news section. The thing with phpBB is that every page has an php and html counterpart. I hope I didnt missunterstand it. I created a custom page and it has a custom.php and custom_body.html. So any advice how I could add a blog in this case?

    custom.php > http://pastebin.com/QrB9yCd5
    custom_body.html > http://pastebin.com/vbyVkwK5

    Thanks and best wishes
    Ivan

  • Alex Vallejo
    Alex Vallejo

    Loading a WP environment into a static HTML file is going to increase load time. Just something to think about.

  • disenopop
    disenopop

    Nice piece of code you got there! One quick question: Is there a way to show posts from a certain category only? Hope you can help me. Thanks!

  • A awesome post for quick tricks in html i need some help to convert a complete html 5 ecommerce site convert to woo commerce with cart and client management system

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.