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.
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.
Discover more from WorldOWeb
Subscribe to get the latest posts sent to your email.
Really great & work.. thanks
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
and second time it shows same data of first blog
Do you mean 2 blogs on the same server? If so it’s not really possible, you would be better using the following tutorial which fetches both blogs posts via RSS. https://www.worldoweb.co.uk/2012/display-wordpress-posts-on-another-wp-blog I also created a PHP class from this code. Take a look at https://pastebin.com/8pkMUd6S
works like a charm!!!!!
Good and Great topic. Very helpful.
Hi Tracy
Nice Article
I want to add recent articles to my HTML page. How this can be done.
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
how would I add teaser summary of the post, and have it show an image and the first 100 characters??
Hi Sean. Checkout the code snippet below with the examples for all. I used custom fields for the teaser. Let me know how you get on as this is only a rough late night draft.
https://pastebin.com/pypCSRfW
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!
Thanks for the kind words. I can incorporate your suggestion into a tutorial for the future.
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 https://bojanarcon.com/ihif/ .
* Link to blog in Polish is https://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.
Does your link to wp-blog-header.php look like this?
<?php require(‘blog/wp-blog-header.php’);?>
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?
Great question Lawrence. I will have to test it out and let you know. What is your current WP setup?
I found the solution, it’s simple:
That works well
Works perfectly – thanks greatly!
Thank you so much for this artciles
is ti possible to show the dates if the two posts are being published for the same day?
You want to display the date of each post, even if 2 have been posted on the same day?
Use the_date See example in comment URL below
https://www.worldoweb.co.uk/2012/display-your-wordpress-recent-posts-on-a-static-page#comment-804774077
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
The white screen of death! It’s not as bad as it sounds. Double check that there is no whitespace directly before the php opening tags and after the closing php tags in your functions.php.
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? 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?
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
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?
Do you have a forward slash immediately before the blog folder in your php require path? If so remove it and try again. Another question: is that sub directory also a subdomain?
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:
No probs. I am just trying to eliminate a few possibilities. Can you post the test page to pastebin or alternatively email me
Just emailed you the code for that page…thank you. I
No errors in the code so it is quite possibly the server. I’ve just tested it locally on Nginx and it works fine. Have you checked out the following blog post? https://www.narga.net/avoid-nginx-wordpress-blank-page/
I’m not sure of your server setup ao it also might be worthwhile contacting your host
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
Hi John. This can be done quite easily. Check out https://pastebin.com/TWKQR9ZJ
I have added comments to the snippet to make it easier to follow.
Thanks for your kind words. :0)
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
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 @
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 John. Your comment went into my Pending section. I was travelling back from my holiday yesterday so didn’t get chance to approve it.
Sorry Chirag. I’m looking into the problem. Thanks for reporting it
Fixed it now. It must be an update that has corrupted my syntax highlighter plugin. Now I’ll check the rest.
Its Niceeeee. one .. And I got it is working fine for me. thanks a lot……
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 > https://pastebin.com/QrB9yCd5
custom_body.html > https://pastebin.com/vbyVkwK5
Thanks and best wishes
Ivan
phpBB/ WP integration is not something I have ever done but might give it a try in the future. Did you add the 2nd code snippet in the blog post to the custom_body.php? Have you installed WP on the same server?
Hello Tracy. First I want to thank you for the fast reply. Yes Ive added the 2nd code snippet, it looks like this: https://pastebin.com/PhReAhXQ
WP is located in a folder called “blog” on the same server like the phpBB board.
Does anything display or do you get any PHP error messages?
Could be a number of things. It could be that the path to the file within the PHP include is incorrect or .htaccess problems. Can you provide me with a URL? Email it me if required.
Loading a WP environment into a static HTML file is going to increase load time. Just something to think about.
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!
On line 2 of the PHP snippet you can add category parameter to the array.
‘category’ =>’ID’
Replace ID with the category ID number which can be found in the following admin section.
Posts -> Categories
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
© 2024 WorldOWeb. All rights reserved