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 );
}

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 );
}

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 );

Leave a Reply