I have a non plugin script that has it’s own database and I want to use it with WordPress. How can I add custom php code that connects to this separate database in my wordpress pages? It needs to go at the top of each page above <html>
I am using Genesis Framework.
Any help is appreciated.
Here is the custom function I have in my functions.php file
/** Activate IP Timer Countdown */
add_action( 'init', 'your_script_function' );
function your_script_function() {
$notimeleft_str = "There is no time left";
$hours = 48;
$minutes = 0;
$days = 0;
$months = 0;
$db_host = "localhost";
$db_user = "xxxxx";
$db_pass = "xxxxx";
$db_dbname = "xxxxx";
$str = "+" . $months . ' months +' . $days . ' days +' . $hours . ' hours +' . $minutes . ' minutes';
// DO NOT EDIT BELOW THIS LINE!
date_default_timezone_set('UTC');
include_once("mysql.class.php");
$db = new MySQL(true, $db_dbname, $db_host, $db_user, $db_pass);
$db->ThrowExceptions = true;
$script_name = $_SERVER["PHP_SELF"];
$cookie_expire = 60*60*24*365*20;
$str_interval = "+" . $months . ' months +' . $days . ' days +' . $hours . ' hours +' . $minutes . ' minutes';
if($_COOKIE['cd_until']) $cookie = json_decode($_COOKIE['cd_until'], true);
else $cookie = Array();
if(isset($_GET["reset"])) {
//$db->DeleteRows("cd_until", Array("ip" => '"' . $_SERVER["REMOTE_ADDR"] . '"', "page" => '"' . $script_name . '"'));
unset($cookie[$script_name]);
header("Location: " . $_SERVER["PHP_SELF"]);
}
else {
$query = "SELECT * FROM cd_until WHERE ip='" . $_SERVER["REMOTE_ADDR"] . "' AND page='" . $script_name . "'";
$value = $db->QuerySingleRow($query);
if($value) {
$thedatetime = new DateTime();
$thedatetime->setTimestamp(intval($value->until));
$cookie[$script_name] = intval($value->until);
} else {
if($cookie[$script_name]) {
$thedatetime = new DateTime();
$thedatetime->setTimestamp( intval( $cookie[$script_name] ) );
} else {
$thedatetime = new DateTime();
$thedatetime->modify( $str_interval );
$cookie[$script_name] = intval( $thedatetime->format("U") );
}
$new_id = $db->InsertRow(
"cd_until",
Array(
"ip" => '"' . $_SERVER["REMOTE_ADDR"] . '"',
"until" => intval( $thedatetime->format("U") ),
"page" => '"' . $script_name . '"'
)
);
}
}
setcookie("cd_until", json_encode($cookie), time() + $cookie_expire, "/");
}
You could use a WordPress action hook. For example, you could add the following code to your themes functions.php file:
The first line makes WordPress execute the ‘your_script_function’ function on initialization. You can add your script in that function.
Alternatively, you could add the code to a plugin. This would be easier for using/installing the script on multiple WordPress installations. It is indeed not recommended to edit the WordPress core files.
For more information about WordPress actions and hooks:
I’d say the wp-load.php file would be a safe place to put it, as it’s included on all pages that use the WP functions.