Create a “Recent Posts” Module Outside of WordPress
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
Be Heard!
Share your thoughts with fellow developers of all skill levels! I want to hear from you!
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/
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:
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
@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