Auto-enable WP_DEBUG with a cookie

One of the most important things to do when working on new themes, plugins, or debugging issues in WordPress is to turn on WP_DEBUG.  According to the Codex:

WP_DEBUG is a PHP constant (a permanent global variable) that can be used to trigger the “debug” mode throughout WordPress. It is assumed to be false by default and is usually set to true in the wp-config.php file on development copies of WordPress.

It’s common to edit the wp-config.php file every time you want to turn this off and on, but another way to do it is via a secret cookie:

if ( isset( $_COOKIE[ 'wp_secret_debug_cookie' ] ) ) {
	define( 'WP_DEBUG', true );
}Code language: PHP (php)

I also like to pair my WP_DEBUG with these extra settings:

if ( defined( 'WP_DEBUG' ) && true === WP_DEBUG ) {
	define( 'WP_DEBUG_LOG', true );
	define( 'SCRIPT_DEBUG', true );
	define( 'WP_DEBUG_DISPLAY', true );
	define( 'CONCATENATE_SCRIPTS', false );
	define( 'SAVEQUERIES', true );
}Code language: JavaScript (javascript)

I set the cookie in an mu-plugin like this (Note: This code could definitely be improved)

function emrikol_admin_debug() {
	if ( is_super_admin() ) {
		setcookie( 'wp_secret_debug_cookie', 'on', time() + 86400, '/', wp_parse_url( get_site_url(), PHP_URL_HOST ) );
		setcookie( 'wp_secret_debug_cookie', 'on', time() + 86400, '/', wp_parse_url( get_home_url(), PHP_URL_HOST ) );
		setcookie( 'wp_secret_debug_cookie', 'on', time() + 86400, '/', wp_parse_url( get_admin_url(), PHP_URL_HOST ) );

		// Allow sites to set extra domains to add cookie to--good for subdomain multisite.
		$extra_domains = apply_filters( 'emrikol_admin_debug_domain', false );
		if ( false !== $extra_domains ) {
			if ( is_array( $extra_domains ) ) {
				foreach ( $extra_domains as $extra_domain ) {
					setcookie( 'wp_secret_debug_cookie', 'on', time() + 86400, '/', $extra_domain );
			} else {
					setcookie( 'wp_secret_debug_cookie', 'on', time() + 86400, '/', $extra_domains );
add_action( 'init', 'emrikol_admin_debug', 10 );
add_action( 'admin_init', 'emrikol_admin_debug', 10 );Code language: PHP (php)

Other Posts Not Worth Reading

Hey, You!

Like this kind of garbage? Subscribe for more! I post like once a month or so, unless I found something interesting to write about.


2 responses to “Auto-enable WP_DEBUG with a cookie”

  1. Even better. If you take WP development and therefor PHP development serious you will have xdebug installed and activated. Use this to switch Debugging on and of with an XDebug helper:

    define(‘WP_DEBUG’, $_COOKIE[‘XDEBUG_SESSION’]??false);
    define(‘SCRIPT_DEBUG’, $_COOKIE[‘XDEBUG_SESSION’]??false);

    1. Derrick Avatar

      I appreciate your comment, but I disagree that one has to use Xdebug to take PHP development seriously. What’s important is that you understand the tools you have available to you, and you know how to use them for proper debugging. Even if that’s error_log() and die( __LINE__ ).

Leave a Reply