Treehouse

Create a “Recent Posts” Module Outside of WordPress

By on  

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 '';

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().

ydkjs-1.png

Recent Features

  • CSS vs. JS Animation: Which is Faster?

    How is it possible that JavaScript-based animation has secretly always been as fast — or faster — than CSS transitions? And, how is it possible that Adobe and Google consistently release media-rich mobile sites that rival the performance of native apps? This article serves as a point-by-point...

  • CSS @supports

    Feature detection via JavaScript is a client side best practice and for all the right reasons, but unfortunately that same functionality hasn't been available within CSS.  What we end up doing is repeating the same properties multiple times with each browser prefix.  Yuck.  Another thing we...

Incredible Demos

  • background-size Matters

    It's something that makes all men live in fear, and are often uncertain of. It's never spoken, but the curiosity is always there. Nine out of ten women agree in the affirmative. Advertisers do their best to make us feel inadequate but...

  • “Top” Watermark Using MooTools

    Whenever you have a long page worth of content, you generally want to add a "top" anchor link at the bottom of the page so that your user doesn't have to scroll forever to get to the top. The only problem with this method is...

Discussion

  1. Ben

    I was wondering why you are still using mysql_ commands. They are insecure and really should be replaced with imo PDO. I refer you to
    http://www.webdevrefinery.com/forums/topic/1272-your-mysql-code-sucks/

  2. Michael Bryan

    just out of curiosity, why have you never used wordpress as a full CMS?

  3. @Michael Bryan: Not been allowed to at my day job.

  4. 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.

  5. 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 ;)

  6. Thanks for this tip david.

  7. @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?

  8. Exactly but the convenience will outweigh the overhead once we decide to build more than basic stuff.

  9. I thonk it is better you include the wp-load.php and use the WordPress default functions.

  10. 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.

  11. 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.

  12. 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…

  13. @Nickolas Simard: Aaaah, come on… Code not rendering :S

    Only 1 simply include at the beginning of the page:

    phpStart
    /* Short and sweet */
    define(‘WP_USE_THEMES’, false);
    require(‘./blog/wp-blog-header.php’);
    phpEnd

    Then simple calls to the WP function:

    http://codex.wordpress.org/Integrating_WordPress_with_Your_Website#Examples

    • Becmen

      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.

  14. @Nickolas: Seems your code broke :(

  15. Bruno Lustosa

    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.

  16. asd

    mixed html with php.. god damned.. it sucks!

  17. qwe

    mixed html with php.. god damned.. it sucks!

  18. alelo

    <a href="/blog/”>

    better? :)

  19. alelo

    damn :/
    http://pastebin.com/raw.php?i=3Sgz3FgL
    better? *delete post above please*

  20. @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! ^^

  21. Andres Freese

    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!

  22. Jason Andreoni

    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!

  23. Michael Houghton

    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.

  24. @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.

  25. Michael Houghton

    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.

  26. Thank you for starting this excellent thread. I’ve been looking info like this.

  27. 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 :)

  28. Michael Houghton

    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.

  29. Michael Houghton

    @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:

  30. Dave33

    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

  31. Fantastic thank you! Was trying to find a solution that didn’t use wordpress’s functions :D

  32. 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.

  33. Senyo

    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?

  34. 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!

  35. 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’

  36. [...] Create a “Recent Posts” Module Outside of WordPress This entry was posted in PHP, Uncategorized and tagged get-posts, include, module, oftentimes-the-client, postpost-title, september, while, within-the-website, within-the-wordpress by Carl Howell. Bookmark the permalink. [...]

  37. But why are you not using the standard build-in function of the wordpress for showing the articles on the homepage ?

  38. Maxi

    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

    require('/path-to-wordpress/wp-load.php');
    $current_user = wp_get_current_user();
    echo $current_user->ID;

    I always receive a 0.

    If I print current defined variables I get an empty object

    [current_user] => WP_User Object
    (
    [data] =>
    [ID] => 0
    [caps] => Array
    (
    )

    [cap_key] =>
    [roles] => Array
    (
    )

    [allcaps] => Array
    (
    )

    [filter] =>
    )

    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

    • Maxi

      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!

  39. [...] Create a “Recent Posts” Module Outside of WordPress [...]

  40. Ivor Humphreys

    Many thanks for posting this, David. It works beautifully and is easily adapted as seen here:

    http://www.friendsoflondiani.com/

    • Ivor Humphreys

      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!

  41. David Walsh is TOTALLY EPIC!! haha :)
    Thanks for the tip Sir, we’ve also seen your php calendar… bravo!

    Cheers,
    C.

  42. 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

  43. [...] when you include the wp-load.php file, you’ll get all those wordpress function , so you can create something new like separate recent comment, etc. source [...]

  44. Faisal

    How can I filter the posts by a specific category?

  45. Thank you for this post. You saved my day :)

    + ★

  46. […] Create a “Recent Posts” Module Outside of WordPress […]

  47. 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.

  48. […] Create a “Recent Posts” Module Outside of WordPress […]

Wrap your code in <pre class="{language}"></pre> tags, link to a GitHub gist, JSFiddle fiddle, or CodePen pen to embed!