Skip navigation
Tyssen Design — Brisbane Freelance Web Developer
(07) 3300 3303

Connecting to an external database from within a Wordpress post

By John Faulds /

For the article I wrote recently on web design galleries, I compiled a table of the galleries in a MySQL database. To be able to display the table and the associated charts and other statistics that went with it, I needed to be able to connect to this external database from within Wordpress.

A post on the Wordpress support forum suggested creating a separate template and adding an include which contained the database connection string to that template. That's what I did for the page to display the table as the design for the page called for a single column rather than two like the rest of the site, but you can only assign different templates to pages, not posts, within Wordpress; posts in Wordpress are all displayed by single.php. That wasn't an issue though because I just placed a conditional at the top of the single template that said if(is_single(XXX)) include('database_connection.php');.

That worked fine for the post, but what I didn't realise at first was that it had broken the site's feed because the database connection include wasn't available to the files that create the feed which can be found in /wp-includes/ – feed-atom.php, feed-rdf.php, feed-rss.php and feed-rss2.php. So when the feed file was parsing the post and came to a call to a PHP function contained in an include file that it didn't have access to, it threw an error.

The solution to this was simple too though: just take the include calls out of the template and include them in the actual post themselves (before everything else) as everything included in the post gets passed to the feed-creating files. I was already using the Exec-PHP plugin to enable the use of PHP within my posts, so it just meant linking to the includes from a different part of the page; a part of the page to which the feed files had access.