Create a “Recent Posts” Module Outside of WordPress
This post was rewritten on Monday, September 24, 2012
I've never created a complete client website using WordPress, but many of those websites do have a WordPress blog to compliment the website. Oftentimes the client will want to list recent blog posts within the website, not within the WordPress shell. No problem -- creating a recent posts module, or any Query-based usage of WordPress posts, is incredibly easy!
The PHP
The key to using WordPress outside of WordPress is include the wp-load.php
file:
// Include the wp-load'er include('wp-load.php'); // Get the last 10 posts // Returns posts as arrays instead of get_posts' objects $recent_posts = wp_get_recent_posts(array( 'numberposts' => 10 )); // Do something with them echo '
- ';
foreach($recent_posts as $post) {
echo '
- ', $post['post_title'], ' '; } echo '
Once the wp-load.php
file is included, the entire wealth of WordPress functions is provided to you. While the sample code above gets recent posts, you can do your own custom queries with WP_Query or get_posts().
I was wondering why you are still using
mysql_
commands. They are insecure and really should be replaced with imo PDO. I refer you tohttp://www.webdevrefinery.com/forums/topic/1272-your-mysql-code-sucks/
Even better than that is using javascript code to get latest posts because sites like Weebly and other content creation sites support javascript which means any site that allows you to input javascript you can display a widget with your blogs latest posts. Check out http://affiliateswitchblade.com/blog/postsscroller
just out of curiosity, why have you never used wordpress as a full CMS?
@Michael Bryan: Not been allowed to at my day job.
I did this a few weeks back. I was glad how easy it was. Just added it to my home page and created some JavaScript to transition between them just to add a little flare.
P.S., requiring JavaScript just to post a comment is not very user-friendly.
Alternatively you can just load WordPress by including wp-load.php and use WordPress functions on those pages if you need to do more than just basic stuff ;)
Thanks for this tip david.
@Ben:
mysql_
functions are the least common denominator.@Ashfame: Why bring in a bunch of extra overhead if all you want to do is get a few records from your database?
Exactly but the convenience will outweigh the overhead once we decide to build more than basic stuff.
I thonk it is better you include the wp-load.php and use the WordPress default functions.
If you don’t want to bring in the WP functions, I would still use a DB class like PDO. It’s better in the long run.
MySQL library has been deprecated for many many years, it’s recommended to use at least MySQLi, or PDO (like others have mentioned). Any good host would have both installed. Of course, using a WordPress API (if it has one) is by far the best idea, as you’re no longer relying on internal WordPress implementation details.
Seriously, I’m surprised you’re not using the overhead include in order to use the WP function as @Ashfame stated!
Only 1 simply include at the beginning of the page:
Then simple calls to the WP function:
– <a href="” rel=”bookmark” title=”Permalien vers “>
That’s how I did it on my day job… and it’s working PER-FECT-LY!
I got the code from the WP dev blog, IIRC…
@Nickolas Simard: Aaaah, come on… Code not rendering :S
Only 1 simply include at the beginning of the page:
Then simple calls to the WP function:
http://codex.wordpress.org/Integrating_WordPress_with_Your_Website#Examples
Thank you! I was Googling for instructions on how to do this, and everything that came up referenced wp-load instead of wp-blog-header. Your links put me on the right track.
@Nickolas: Seems your code broke :(
Hello, David.
The column you picked for the permalink may work in your particular case, but it won’t work for everyone, because the link structure can be changed, and can depend on other things (post date and category, for example).
The proper way to generate the permalink is to call get_permalink(), passing the post ID as a parameter, but of course, that would depend on WordPress.
The function itself gets the permalink structure from the DB, and makes a big str_replace, swapping the %category% and other variables for their correspondents.
mixed html with php.. god damned.. it sucks!
mixed html with php.. god damned.. it sucks!
<a href="/blog/”>
better? :)
damn :/
http://pastebin.com/raw.php?i=3Sgz3FgL
better? *delete post above please*
@Daniel15: Yeah, that’s why I reposted with “phpStart” and “phpEnd” for the header includes…
and http://codex.wordpress.org/Integrating_WordPress_with_Your_Website#Examples
for the loop generating the list. Hope THAT work though! ^^
I have a short question regarding showing information from WordPress outside of the WordPress installation: For a project at the company I work, I need a Script that shows up the search result count of a wordpress blog, outside of it. What I mean is a separate website, that is used as a metasearch engine (searches in different blogs), I have to show the search result number from a wordpress blog. There are different approaches that I have in mind. I could maybe use Tip Nr. 8 from this Smashing Magazine Article:
http://www.smashingmagazine.com/2009/06/10/10-useful-wordpress-loop-hacks/
which means creating my own WordPress Loop using The WP_Query Object in a File at the root folder and then inlude this php file in the separate website? or as a second approach I could try and modify this script from the wordpress forum:
http://wordpress.org/support/topic/226572?replies=15
so that it pulls, not the the number of posts in the WP database but the search results count. Only I don’t know how to achieve it.
Of course the query:
http://pastebin.com/Saqznh1N
hast to be different, but I´m really not a php master. Thank you very much for your answers! Maybe if the question or better the answer is worth it for you, you could post it as a tutorial in the near future in your awesome blog David. Thanks!
Holy crap, I was JUST looking for this exact thing last night. Poking around on WordPress’ forums, I found a few helpful comments.
I’ll definitely be giving this a run-through tonight. Thanks!
A point worth noting is that whatever the merits of using wordpress’s builtins versus this (and I must say generally for preserving encapsulation David’s solution is not the best idea), the integration with wordpress is tricky if you want to import all that code into another reasonably complex app from within a function or a PHP template rendered from a function; it appears simply not to work.
I don’t much like the pure SQL solution suggested here, but David’s technique does at least work.
@Michael Houghton: Hmm, you’re absolutely right, I forgot about the “PHP template”-kind of website… I guess we can’t always think of all possibilities right away.
Well in this case there’s no real reason it shouldn’t work.
The problem seems to be that the WP ‘Codex official’ way to do this integration fails if you try to do it from anything other than the top-level scope. You start needing to know a list of wordpress globals which you must define. This is surprisingly bad.
So I am reluctantly using David’s method (though my codebase already has ADODB in it so I’m not using the mysql_ functions). The dependency on knowing the database structure is small enough and not critical enough to worry about.
Thank you for starting this excellent thread. I’ve been looking info like this.
I did something similar on my website recently. Having queries on the page seemed a bit messy, and the WordPress way had a lot of global variables and also seemed messy. I ended up writing a script that loaded the RSS feed (via SimpleXML), got the data I needed, and output a serialised PHP array into a file. Then the page on my site just loads that serialised array from file (or it could even be from cache) when it needs it. Saves the overheads of database queries or XML parsing on every load, and is quite a bit faster :)
Daniel15: Speed is far less of an issue here than you might think, actually. If either the blog or the site you’re pulling headlines on is browsed fairly frequently, there’s a good chance that PHP will have kept the WP database connection open and that the query result will be in MySQL’s query cache, which is a pretty efficient thing.
Having said that, your approach has the advantage of working regardless of where the blog is hosted, and indeed regardless of which app the blog is running on, which makes it the cleanest solution.
@Bruno Lustosa: another option is just to use the “guid” field from the posts table, which stores in the canonical form for the script (http://servername/?p=nnn)
While this isn’t the customised permalink, wordpress immediately serves a 301 (moved permanently) redirect to the custom permalink URL, which search engines should obey.
@Bruno Lustosa:
Fairly new to WP. Is it possible to generate posts dynamically in wordpress? For example, I have listing data that gets created or updated daily and I’d like to push that data to my blog as posts dynamically. I assume this is possible? I’d also like to dynamically remove a post once the item is gone. The data will always look the same in the posts.
If anyone could point me in the right direction I would appreciate it.
Thanks,
Dave
Fantastic thank you! Was trying to find a solution that didn’t use wordpress’s functions :D
You could certainly see your expertise within the work you write. The arena hopes for even more passionate writers like you who are not afraid to mention how they believe. All the time follow your heart.
I have created a website and want to add a blog page to it. Can someone please give me an idea on how to do this?
Ah, perfect. Thanks! Needed to put latest blog post links on a site and didn’t want to bother one of our programmers…I knew there had to be a handy code snippet to do it with. I just had to tweak the code for my permalink structure! Thanks!
It’s worth noting that if you use the code as is, it will display all kinds of posts e.g. attachments and posts of any status e.g. draft, scheduled etc
Insert these parameters into the array for a bit more control over what is displayed.
‘post_type’ => ‘post’,
‘post_status’ => ‘publish’
But why are you not using the standard build-in function of the wordpress for showing the articles on the homepage ?
Hi David,
maybe you or one of your readers can help me.
I can execute your code and display latest posts outside wordpress directory.
What I can’t succeed is retreiving logged-in user informations.
if I
I always receive a 0.
If I print current defined variables I get an empty object
which explay the previous ID = 0.
Nothing happen even using
get_currentuserinfo()
What am I missing?
Please could you help me in retrieving current logged in user outside wordpress directory?
Many thanks
Guys I made it!
It was something in wordpress config.
I changed some settings (site URL different from wordpress URL, Anyone can register flag, and some others) and everything worked fine.
Bye!
Many thanks for posting this, David. It works beautifully and is easily adapted as seen here:
http://www.friendsoflondiani.com/
The WordPress site was subsequently hacked and is currently down so the link above no longer shows WP posts but rather news items from the site itself. But it did work beautifully!
David Walsh is TOTALLY EPIC!! haha :)
Thanks for the tip Sir, we’ve also seen your php calendar… bravo!
Cheers,
C.
Hi David,
Yet another newbie referred by Boulder Information (links to this page at your site)…
I have what I suspect is an incredibly simple question.
I use Twenty-Eleven and the Recent Posts widget in JetPack. (Blog is here: AWildDuck d0t com)
Yet this only puts the RP list on my home page. I want it on EVERY page…
I don’t see any sidebar on the individual posts. How can I get the Recent Posts list onto every post?
I very much appreciate your help. Thank you!
–Ellery
How can I filter the posts by a specific category?
Thank you for this post. You saved my day :)
+ ★
Thanks David, worked a treat.
for anyone interested in page speed effect of this, iCalculator homepage went from 6.8kb to 7.2kb.
That’s pretty light given that the include will allow access to all of the wordpress functionality.
Like you, I prefer to develop my own bespoke sites, the implementation of wordpress was to allow a new staff member to add tax articles and information in support of the main salary calculators.
I needed the flex of full control and a good blogging tool, I don’t think I could ever fully walk the root of tying into another developers framework. Subjective I guess.
Is there a plugin to help cut and paste code to my website. I would like recent posts on my non-WordPress website. I don’t know php very well.
Hello David,
Thank you for nice tutorial, following it and some comments i came up with something almost perfect for me: http://lazer-medpark.md/latest_test2.php
All i need for it to be 100% perfect is to add links to titles, so the titles would lead to full article, or perhaps some sort of Read more… link at the end of each intro text.
Second is a small version of first picture used in the post.
Could you please give me an idea how to do that?
Thanks a lot in advance,
Regards!
I’m sorry, forgot to include my code: http://pastebin.com/0Fn3QLPt
Thanks again.
For calling posts outside blog. I think working with RSS feed and manipulating them is best.
Fantastic bit of code, works perfectly!
Once again you are a huge help, thanks!
Thanks! So simple and elegant!