Using non-plugin third-party scripts with WordPress 2.1.2+

It’s probably a minority, but WordPress users who are using third-party scripts (like Enthusiast) directly coded/included into their WP templates (read: not included as a plugin) who have upgraded to 2.1.2 and higher may experience problems getting their blogs to work. This is due to a conflict between the database link that WordPress uses and the database link that your other script is using. Users get a variation of the following line:

Warning: mysql_error(): X is not a valid MySQL-Link resource in (path) on line Y

Basically, PHP 4.x’s mysql_connect function—which lets the script talk to your database server—gets confused as to which connection is active. This has happened to me since the script I’m using for my downloads (here in this archive, in my wallpapers archive, and the various downloadable things in my other sites) is not set up as a WP plugin; I just do a series of includes in my WP templates. So when I updated to 2.1.2, I ran into problems.

I meant to address this earlier, when I came across the problem here in my tech blog/scripts archive, but got sidetracked. I was only reminded of it when I came across some open support posts at CodeGrrl.

The fix? It’s rather simple. After every chunk of code (or PHP include) you put in your WP template that accesses the database server (read: it generates the above error), add this line of code:

// reconnect to WordPress database
$wpdb->select( DB_NAME );

(Actually, the first line isn’t that important. But comments are good for you.) This might not work for every instance; basically it just changes the database that the link connection is using. However, it’s possible that the new database user the connection is, ah, using, can’t access your WordPress database. So if the above doesn’t work for you, you’ll have to use something else:

// reconnect to WordPress database
$wpdb = new wpdb( DB_USER, DB_PASSWORD, DB_NAME, DB_HOST );

That should basically restart the WordPress database. I haven’t tested the second option, so if you end up needing to use the second option and get problems, let me know. :)

If you’re using Enthusiast with WordPress 2.1.2+ and need a better example, here’s something that may be clearer:

// show joined listings
require( 'config.php' );
$show_list = true;
include $path . 'show_joined.php';
// reconnect to WordPress database
$wpdb->select( DB_NAME );

Do the same for all the other snippets and you should be fine.