The snippet enables WordPress Debugging Mode (WP_DEBUG) based on the subdomain or path of the request, activating debugging features in development or staging environments while leaving them disabled in production.
The code is wrapped in an anonymous function to prevent variable conflicts and eliminate potential confusion with other parts of the configuration file.
Include this code in the wp-config.php
file, where it checks for subdomains or paths containing common indicators for development environments and sets the WP_DEBUG constant accordingly. Possible concerns include security, as malicious users may manipulate the headers to enable debugging.
/**
* WordPress Debugging Mode
*
* Enable WP_DEBUG for specific development-related subdomains or paths.
* Use with caution in a live environment.
*/
call_user_func( function() {
// Whitelist allowed subdomains
$allowed_subdomains = ['dev', 'staging', 'test'];
// Get host and sanitize
$host = $_SERVER['HTTP_HOST'] ?? '';
$host = filter_var( $host, FILTER_SANITIZE_URL );
// Get subdomain
$uri_parts = explode( '.', $host );
$subdomain = array_shift( $uri_parts );
// Get first segment of URL path
$uri_parts = explode( '/', $_SERVER['REQUEST_URI'] );
$path_first_segment = $uri_parts[1] ?? '';
// Determine if it's a debug environment
$is_debug = in_array( $subdomain, $allowed_subdomains) ||
in_array( $path_first_segment, $allowed_subdomains );
// Define wp_debug
define('WP_DEBUG', $is_debug);
});