WordPress
Use one DB connection on your custom wordpress install
Like most people who use WordPress, I have hacked a few installs 6 ways from Sunday for some of my projects. While digging through my hacks I had noticed that the script was connecting to my database TWICE per client … once for my website it’s self, then once for WordPress’ needs. This seemed like an awful waste especially considering how much traffic the site can get … so why not share the connection resource [while effectively DOUBLING the amount of people who can connect to your blog — since 2 - 1 = 1
]??
This is how I hacked WordPress to reuse an existing DB connection …
WordPress, meet my web site
I started with the root of the script, ./index.php
, and added in my global include file [.gfl
== global function library, which, among other things, connects to the DB for me]. This way no matter what WordPress does on the front end, it will also have all my web site’s functions as well.
<?php
require("../global.gfl");
/* Short and sweet */
define('WP_USE_THEMES', true);
require('./wp-blog-header.php');
?>
Now play nice!
After changing my mysql_connect resource to a global variable:
<?php
global $dbResource;
$dbResource = mysql_connect("host","user","pass");
mysql_select_db("db");
?>
I did a quick search for the string "mysql_connect" within my WordPress directory I found it living in ./wp-includes/wp-db.php
. I changed …
<?php
function __construct($dbuser, $dbpassword, $dbname, $dbhost) {
# Code omitted
$this->dbh = @mysql_connect($dbhost, $dbuser, $dbpassword, true);
# Code omitted
}
?>
… to …
<?php
function __construct($dbuser, $dbpassword, $dbname, $dbhost, true) {
global $dbResource;
if (is_resource($dbResource)) {
# For the front-end ...
$this->dbh = $dbResource;
} else {
# For wp-admin ...
# Code omitted
$this->dbh = @mysql_connect($dbhost,$dbuser,$dbpassword);
# Code omitted
}
}
?>
Simple enough!
Comments, critiques, suggestions, recommendations, changes, etc etc etc are always welcome!
Read Full Post | Make a Comment ( 3 so far )