1
votes

I'm trying to include a custom cookie in my Wordpress site, and I'm having some issues. I tracked down the last possible place for me to insert my cookie before headers got sent, which appears to be just before the last line in my wp-config.php

So I threw a require_once('path/to/cookie.php') at the end of my wp-config.php and was able to set the cookie. Whoopie. But each cookie's unique id needs to be stored in my database. So I invoked wp-load.php so I'd have the $wpdb global available, and then started attempting queries. 500 errors abound. What am I missing?

Here's the end of my wp-config.php

/* That's all, stop editing! Happy blogging. */
/** Absolute path to the WordPress directory. */
if ( !defined('ABSPATH') )
    define('ABSPATH', dirname(__FILE__) . '/');
/** Sets up WordPress vars and included files. */
require_once(ABSPATH . '/wp-content/plugins/myPlugin/cookie.php');
require_once(ABSPATH . 'wp-settings.php');

And here's cookie.php

$path = $_SERVER['DOCUMENT_ROOT']; 
require_once $path . '/wp-load.php';

function rand_string( $length ) {
    $chars = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789";  

    $size = strlen( $chars );
    for( $i = 0; $i < $length; $i++ ) {
        $str .= $chars[ rand( 0, $size - 1 ) ];
    }

    return $str;
}

function check_id($id){
    global $wpdb;
    $results = $wpdb->get_results("SELECT id FROM visitors WHERE userid = '$id'");
    if(mysqli_num_rows($results) > 0){
        return false;
    } else {
        return true;
    }
}

if(!isset($_COOKIE['visitor'])){
    $key = false;
    while($key == false){
        if(check_id($userid = rand_string(32))){
            $key = true;        
        }
    }
    setcookie("visitor", $userid, time() + ((86400 * 30)*12), "/", "site.com");
}
1
Please check my answer and reply your feedback. - PPL

1 Answers

0
votes

You can load WP files In cookie.php:

define( 'BLOCK_LOAD', true );
require_once( $_SERVER['DOCUMENT_ROOT'] . '/wp-config.php' );
require_once( $_SERVER['DOCUMENT_ROOT'] . '/wp-includes/wp-db.php' );
$wpdb = new wpdb( DB_USER, DB_PASSWORD, DB_NAME, DB_HOST);

Hope this works for you.