Skip to the content...

Welcome to the David Walsh Blog. I'm a MooTools, Dojo, jQuery, CSS, and PHP Web Developer located in Madison, Wisconsin, United States. Please contact me if I can make your experience on my website better.

Create a “Recent Posts” Module Outside of WordPress

31 Responses »

The websites I create are never powered by WordPress. Sure I may add a blog to the website but I've never created a client website that was run by the powerful blogging software. In an effort to tie the website and blog together, I'll usually do some quick PHP/MySQL programming to pull in recent blog post titles and links to the individual posts. Here's the PHP and MySQL that accomplishes that task.

The SQL

SELECT post_title, post_name 
FROM wp_posts 
WHERE post_type = 'post' 
AND post_status = 'publish' 
ORDER BY post_date DESC 
LIMIT 5

I'm simply choosing to pull the post title and slug -- you can use "*" to pull in all fields or select additional fields by naming them. The key to the SQL is making sure you use the WHERE conditionals above so you avoid pulling in revisions and unpublished posts.

The PHP

$query = "SELECT post_title, post_name FROM wp_posts WHERE post_type = 'post' AND post_status = 'publish' ORDER BY post_date DESC LIMIT 5";
$result = mysql_query($query,$dblink);
if(mysql_num_rows($result)) {
	echo '<ul>';
	while($post = mysql_fetch_assoc($result)) {
		echo '<li><a href="/blog/',$post['post_name'],'">',stripslashes($post['post_title']),'</a></li>';
	}
	echo '</ul>';
}

The PHP above outputs the posts returned by our query into a nice UL/LI list. As always, feel free to style the list as you wish!

Discussion

  1. ben
    April 16, 2010 @ 8:44 am

    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
    April 16, 2010 @ 8:58 am

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

  3. April 16, 2010 @ 9:11 am

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

  4. April 16, 2010 @ 9:22 am

    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. April 16, 2010 @ 11:30 am

    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. April 16, 2010 @ 11:46 am

    Thanks for this tip david.

  7. April 16, 2010 @ 11:59 am

    @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. April 16, 2010 @ 3:07 pm

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

  9. April 16, 2010 @ 3:27 pm

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

  10. April 16, 2010 @ 9:58 pm

    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. April 17, 2010 @ 2:50 am

    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. April 18, 2010 @ 12:20 pm

    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. April 18, 2010 @ 12:25 pm

    @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

  14. April 18, 2010 @ 5:50 pm

    @Nickolas: Seems your code broke :(

  15. bruno lustosa
    April 18, 2010 @ 10:50 pm

    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
    April 19, 2010 @ 5:52 am

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

  17. qwe
    April 19, 2010 @ 5:54 am

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

  18. alelo
    April 19, 2010 @ 6:10 am

    <a href="/blog/”>

    better? :)

  19. alelo
    April 19, 2010 @ 6:13 am

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

  20. April 19, 2010 @ 7:06 am

    @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
    April 21, 2010 @ 6:41 am

    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
    April 21, 2010 @ 9:54 am

    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
    April 29, 2010 @ 10:54 am

    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. April 29, 2010 @ 11:03 am

    @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
    April 29, 2010 @ 11:17 am

    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. April 30, 2010 @ 1:19 pm

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

  27. April 30, 2010 @ 8:48 pm

    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
    May 1, 2010 @ 8:58 am

    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
    May 3, 2010 @ 8:24 am

    @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
    May 14, 2010 @ 8:06 am

    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. May 21, 2010 @ 5:30 am

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

Be Heard!

Share your thoughts with fellow developers of all skill levels! I want to hear from you!

Name*:
Email*:
Website:  
Wrap your code with <code> tags, f00!