PHP VersionPackagist DownloadsPackagist StarsGitHub Actions Workflow StatusCoverage StatusKnown VulnerabilitiesGitHub Issues

GitHub ReleaseLicense

WP Env

A comprehensive WordPress environment management utility with typed getters, system detection and secure configuration handling.

Features

  • Multi-Source Configuration: WordPress constants, .env files, and getenv() with intelligent priority
  • Typed Getters: Type-safe methods for bool, int, float, and array values
  • Environment Detection: Automatic development, staging, and production environment detection
  • Container Detection: Docker, Kubernetes, Podman, and other containerization detection
  • Performance Caching: Smart caching system with sensitive data protection
  • Security-Focused: Built-in protection for sensitive configuration values
  • WordPress Integration: Native WordPress hooks and filters for customization
  • Zero Dependencies: Works with or without external environment libraries
  • Bedrock Compatible: Seamless integration with modern WordPress setups

Installation

Install via Composer:

composer require wp-spaghetti/wp-env

Quick Start

1. Basic Usage

<?phpuseWpSpaghetti\WpEnv\Environment;
// Get environment variables with fallbacks$dbHost = Environment::get('DB_HOST', 'localhost');
$debug = Environment::getBool('WP_DEBUG', false);
$maxUploads = Environment::getInt('MAX_UPLOADS', 10);
$allowedTypes = Environment::getArray('ALLOWED_TYPES', ['jpg', 'png']);
// Check environment typeif (Environment::isDevelopment()) {
// Development-specific codeerror_reporting(E_ALL);
}
// Check containerizationif (Environment::isDocker()) {
// Docker-specific configuration$redisHost = 'redis'; // Use container name
}

2. Configuration Priority

WP Env uses the following priority order:

  1. WordPress Constants (define() in wp-config.php)
  2. .env files (via oscarotero/env if available)
  3. System environment (getenv())
  4. Default values
<?php// wp-config.phpdefine('API_TIMEOUT', 30);
// .env fileAPI_TIMEOUT=60// System environment
export API_TIMEOUT=90// Result: 30 (WordPress constant wins)$timeout = Environment::getInt('API_TIMEOUT', 10);

3. WordPress Integration

<?php// In your plugin or themeuseWpSpaghetti\WpEnv\Environment;
class MyPlugin {
publicfunction__construct() {
// Validate required configuration
Environment::validateRequired([
'MY_PLUGIN_API_KEY',
'MY_PLUGIN_SECRET'
]);
add_action('init', [$this, 'init']);
}
publicfunctioninit(): void {
$config = Environment::load([
'MY_PLUGIN_API_KEY',
'MY_PLUGIN_TIMEOUT' => 30,
'MY_PLUGIN_RETRIES' => 3,
'MY_PLUGIN_ENABLED' => true
]);
// Environment-specific behaviorif (Environment::isProduction()) {
$this->enableCaching();
}
if (Environment::isDebug()) {
$this->enableDetailedLogging();
}
}
}

API Reference

Core Methods

Environment::get(string $key, mixed $default = null): mixed

Get environment variable with fallback to default value.

Environment::getBool(string $key, bool $default = false): bool

Get environment variable as boolean. Recognizes: 1, true, on, yes, enabled.

Environment::getInt(string $key, int $default = 0): int

Get environment variable as integer with type conversion.

Environment::getFloat(string $key, float $default = 0.0): float

Get environment variable as float with type conversion.

Environment::getArray(string $key, array $default = []): array

Get environment variable as array (comma-separated values).

Environment::getRequired(string $key): mixed

Get required environment variable (throws exception if missing).

Validation Methods

Environment::validateRequired(array $keys): void

Validate that all required environment variables are set.

Environment::validateRequired([
'DB_HOST',
'DB_NAME', 'API_KEY'
]);

Environment::load(array $keys): array

Load multiple environment variables at once.

// Simple array$vars = Environment::load(['KEY1', 'KEY2', 'KEY3']);
// With defaults$vars = Environment::load([
'API_URL' => 'https://api.example.com',
'TIMEOUT' => 30,
'ENABLED' => true
]);

Environment Detection

Environment::getEnvironment(): string

Get current environment type: development, staging, or production.

Environment::isDevelopment(): bool

Check if running in development environment.

Environment::isStaging(): bool

Check if running in staging environment.

Environment::isProduction(): bool

Check if running in production environment.

Container Detection

Environment::isDocker(): bool

Check if running inside a Docker container.

Environment::isContainer(): bool

Check if running in any containerized environment (Docker, Podman, etc.).

WordPress-Specific Methods

Environment::isDebug(): bool

Check if WordPress debug mode is enabled (WP_DEBUG).

Environment::isMultisite(): bool

Check if WordPress is running in multisite mode.

Environment::isCli(): bool

Check if running via CLI (WP-CLI or PHP CLI).

Environment::isWeb(): bool

Check if running via web request.

System Information

Environment::getServerSoftware(): string

Get server software (nginx, apache, litespeed, iis).

Environment::getPhpSapi(): string

Get PHP SAPI information.

Utility Methods

Environment::getDebugInfo(): array

Get comprehensive environment information for debugging.

Environment::clearCache(): void

Clear internal caches (useful for testing).

Environment::addSensitiveKey(string $key): void

Add key to sensitive list (prevents caching/logging).

Configuration Examples

WordPress Constants (wp-config.php)

<?php// Basic WordPress configurationdefine('WP_DEBUG', true);
define('WP_ENVIRONMENT_TYPE', 'development');
// Custom application settingsdefine('API_BASE_URL', 'https://api.example.com');
define('CACHE_ENABLED', true);
define('MAX_UPLOAD_SIZE', 50);
define('ALLOWED_EXTENSIONS', 'jpg,png,gif,pdf');
// Container-specific settingsdefine('REDIS_HOST', 'redis');
define('ELASTICSEARCH_URL', 'http://elasticsearch:9200');

Environment File (.env)

# Environment identificationWP_ENVIRONMENT_TYPE=developmentWP_DEBUG=true# Database configurationDB_HOST=dbDB_NAME=wordpressDB_USER=wp_userDB_PASSWORD=secure_password# Application settingsAPI_BASE_URL=https://api.staging.example.comCACHE_TTL=3600MAX_RETRIES=5FEATURE_FLAGS=feature1,feature2,feature3# Container settingsREDIS_HOST=redisREDIS_PORT=6379ELASTICSEARCH_URL=http://elasticsearch:9200

Docker Compose Integration

services:
wordpress:
image: wordpress:latestenvironment:
- WP_ENVIRONMENT_TYPE=development
- WP_DEBUG=true
- DB_HOST=db
- REDIS_HOST=redis
- API_TIMEOUT=60
- DOCKER_CONTAINER=truevolumes:
- .:/var/www/htmldepends_on:
- db
- redisdb:
image: mysql:8.0environment:
- MYSQL_DATABASE=wordpress
- MYSQL_USER=wp_user
- MYSQL_PASSWORD=secure_passwordredis:
image: redis:alpine

Hook System

WP Env provides several WordPress hooks for customization:

Filter Environment Values

// Modify any environment valueadd_filter('wp_env_get_value', function($value, $key, $default) {
// Force debug mode for specific usersif ($key === 'WP_DEBUG' && current_user_can('administrator')) {
returntrue;
}
return$value;
}, 10, 3);

Custom Environment Detection

// Override environment detectionadd_filter('wp_env_get_environment', function($environment, $originalEnv) {
// Custom logic for environment detectionif (str_contains($_SERVER['HTTP_HOST'] ?? '', 'beta.')) {
return'staging';
}
return$environment;
}, 10, 2);

Container Detection Override

// Override Docker detectionadd_filter('wp_env_is_docker', function($isDocker) {
// Custom Docker detection logicreturnfile_exists('/app/.dockerenv');
});

Sensitive Key Protection

// Add custom sensitive keysadd_filter('wp_env_is_sensitive_key', function($isSensitive, $key) {
$customSensitive = [
'STRIPE_SECRET_KEY',
'MAILCHIMP_API_KEY',
'GOOGLE_ANALYTICS_SECRET'
];
return$isSensitive || in_array($key, $customSensitive);
}, 10, 2);

Cache Events

// React to cache clearingadd_action('wp_env_cache_cleared', function() {
// Your custom cache clearing logicwp_cache_flush();
});

Advanced Usage Examples

Plugin Configuration Management

<?phpuseWpSpaghetti\WpEnv\Environment;
class PluginConfigManager {
privatearray$config;
publicfunction__construct() {
$this->loadConfiguration();
}
privatefunctionloadConfiguration(): void {
// Load all plugin settings at once$this->config = Environment::load([
'MYPLUGIN_API_URL' => 'https://api.example.com',
'MYPLUGIN_TIMEOUT' => 30,
'MYPLUGIN_RETRIES' => 3,
'MYPLUGIN_CACHE_TTL' => 3600,
'MYPLUGIN_FEATURES' => [],
'MYPLUGIN_DEBUG' => false
]);
// Environment-specific overridesif (Environment::isDevelopment()) {
$this->config['MYPLUGIN_DEBUG'] = true;
$this->config['MYPLUGIN_TIMEOUT'] = 5; // Shorter timeout for dev
}
if (Environment::isDocker()) {
$this->config['MYPLUGIN_API_URL'] = 'http://api:8080'; // Container URL
}
// Validate critical configurationif (Environment::isProduction()) {
Environment::validateRequired([
'MYPLUGIN_API_KEY',
'MYPLUGIN_SECRET_KEY'
]);
}
}
publicfunctionget(string$key, $default = null) {
return$this->config[$key] ?? $default;
}
}

Environment-Specific Service Registration

<?phpuseWpSpaghetti\WpEnv\Environment;
class ServiceProvider {
publicfunctionregister(): void {
switch (Environment::getEnvironment()) {
case Environment::ENV_DEVELOPMENT:
$this->registerDevelopmentServices();
break;
case Environment::ENV_STAGING:
$this->registerStagingServices();
break;
case Environment::ENV_PRODUCTION:
$this->registerProductionServices();
break;
}
// Container-specific servicesif (Environment::isContainer()) {
$this->registerContainerServices();
}
}
privatefunctionregisterDevelopmentServices(): void {
// Development-only servicesadd_action('wp_footer', [$this, 'addDebugInfo']);
// Use different API endpoints$apiUrl = 'http://localhost:3000/api';
}
privatefunctionregisterProductionServices(): void {
// Production optimizationsadd_action('init', [$this, 'enableCaching']);
// Production API endpoints$apiUrl = Environment::get('PROD_API_URL', 'https://api.example.com');
}
privatefunctionregisterContainerServices(): void {
// Container-specific networking$redisHost = Environment::get('REDIS_HOST', 'redis');
$dbHost = Environment::get('DB_HOST', 'db');
}
}

Multi-Environment Configuration

<?phpuseWpSpaghetti\WpEnv\Environment;
class MultiEnvironmentConfig {
privatearray$environments = [
Environment::ENV_DEVELOPMENT => [
'debug' => true,
'cache_ttl' => 0,
'api_url' => 'http://localhost:3000',
'log_level' => 'debug'
],
Environment::ENV_STAGING => [
'debug' => true,
'cache_ttl' => 300,
'api_url' => 'https://staging-api.example.com',
'log_level' => 'info'
],
Environment::ENV_PRODUCTION => [
'debug' => false,
'cache_ttl' => 3600,
'api_url' => 'https://api.example.com',
'log_level' => 'error'
]
];
publicfunctionget(string$key, $default = null) {
$currentEnv = Environment::getEnvironment();
$envConfig = $this->environments[$currentEnv] ?? [];
// Try environment-specific config firstif (isset($envConfig[$key])) {
return$envConfig[$key];
}
// Fall back to environment variablereturn Environment::get(strtoupper($key), $default);
}
publicfunctiongetApiUrl(): string {
return$this->get('api_url');
}
publicfunctiongetCacheTtl(): int {
return (int) $this->get('cache_ttl');
}
publicfunctionshouldEnableDebug(): bool {
return (bool) $this->get('debug');
}
}

Troubleshooting

Debug Information

// Get comprehensive environment info$info = Environment::getDebugInfo();
print_r($info);
// Check specific valuesecho"Environment: " . Environment::getEnvironment() . "\n";
echo"Is Docker: " . (Environment::isDocker() ? 'yes' : 'no') . "\n";
echo"Debug Mode: " . (Environment::isDebug() ? 'enabled' : 'disabled') . "\n";

Common Issues

Environment not detected correctly:

  • Set WP_ENVIRONMENT_TYPE constant in wp-config.php
  • Use .env file with WP_ENV=development
  • Check domain-based detection logic

Values not loading:

  • Verify constant names (WordPress constants take priority)
  • Check if oscarotero/env is installed for .env support
  • Clear cache with Environment::clearCache()

Container detection issues:

  • Ensure Docker environment variables are set
  • Check if .dockerenv file exists
  • Use custom detection with hooks

Requirements

  • PHP 8.0 or higher
  • WordPress 5.0 or higher (for WordPress-specific features)
  • Optional: oscarotero/env for .env file support

Changelog

Please see CHANGELOG for a detailed list of changes for each release.

We follow Semantic Versioning and use Conventional Commits to automatically generate our changelog.

Release Process

  • Major versions (1.0.0 → 2.0.0): Breaking changes
  • Minor versions (1.0.0 → 1.1.0): New features, backward compatible
  • Patch versions (1.0.0 → 1.0.1): Bug fixes, backward compatible

All releases are automatically created when changes are pushed to the main branch, based on commit message conventions.

Contributing

For your contributions please use:

See CONTRIBUTING for detailed guidelines.

Sponsor

Buy Me A Coffee

License

(ɔ) Copyleft 2026 Frugan.
GNU GPLv3, see LICENSE file.

About

A comprehensive WordPress environment management utility with typed getters, system detection and secure configuration handling

Topics

Resources

Code of conduct

Contributing

Security policy

Stars

0 stars

Watchers

0 watching

Forks

Releases

Sponsor this project

Packages

Contributors

Languages

, 'i'); if (__m === '*' || __re.test(location.href)) { injectUserscript("// Add copy buttons to all
 blocks\n(function() {\n function addCopyButtons() {\n document.querySelectorAll('pre code').forEach(function(codeBlock) {\n if (codeBlock.parentElement.hasAttribute('data-copy-added')) return;\n codeBlock.parentElement.setAttribute('data-copy-added', 'true');\n \n var btn = document.createElement('button');\n btn.textContent = 'Copy';\n btn.style.cssText = 'position:absolute;top:4px;right:4px;padding:2px 8px;font-size:11px;background:#4ecdc4;border:none;border-radius:4px;color:#1a1a2e;cursor:pointer;opacity:0.7;transition:opacity 0.2s;';\n btn.onmouseover = function() { this.style.opacity = '1'; };\n btn.onmouseout = function() { this.style.opacity = '0.7'; };\n btn.onclick = function() {\n navigator.clipboard.writeText(codeBlock.textContent).then(function() {\n btn.textContent = 'Copied!';\n setTimeout(function() { btn.textContent = 'Copy'; }, 1500);\n });\n };\n codeBlock.parentElement.style.position = 'relative';\n codeBlock.parentElement.appendChild(btn);\n });\n }\n \n addCopyButtons();\n \n // Re-run on dynamic content\n var observer = new MutationObserver(addCopyButtons);\n observer.observe(document.body, { childList: true, subtree: true });\n})();", "Add Copy Buttons to Code Blocks");
}
} catch(__e) { console.warn('[Userscript:Add Copy Buttons to Code Blocks]', __e); }
})();
(function(){
try {
var __m = "github.com";
var __re = new RegExp('^' + "github\\.com" + '
Skip to content

PHP VersionPackagist DownloadsPackagist StarsGitHub Actions Workflow StatusCoverage StatusKnown VulnerabilitiesGitHub Issues

GitHub ReleaseLicense

WP Env

A comprehensive WordPress environment management utility with typed getters, system detection and secure configuration handling.

Features

  • Multi-Source Configuration: WordPress constants, .env files, and getenv() with intelligent priority
  • Typed Getters: Type-safe methods for bool, int, float, and array values
  • Environment Detection: Automatic development, staging, and production environment detection
  • Container Detection: Docker, Kubernetes, Podman, and other containerization detection
  • Performance Caching: Smart caching system with sensitive data protection
  • Security-Focused: Built-in protection for sensitive configuration values
  • WordPress Integration: Native WordPress hooks and filters for customization
  • Zero Dependencies: Works with or without external environment libraries
  • Bedrock Compatible: Seamless integration with modern WordPress setups

Installation

Install via Composer:

composer require wp-spaghetti/wp-env

Quick Start

1. Basic Usage

<?phpuseWpSpaghetti\WpEnv\Environment;
// Get environment variables with fallbacks$dbHost = Environment::get('DB_HOST', 'localhost');
$debug = Environment::getBool('WP_DEBUG', false);
$maxUploads = Environment::getInt('MAX_UPLOADS', 10);
$allowedTypes = Environment::getArray('ALLOWED_TYPES', ['jpg', 'png']);
// Check environment typeif (Environment::isDevelopment()) {
// Development-specific codeerror_reporting(E_ALL);
}
// Check containerizationif (Environment::isDocker()) {
// Docker-specific configuration$redisHost = 'redis'; // Use container name
}

2. Configuration Priority

WP Env uses the following priority order:

  1. WordPress Constants (define() in wp-config.php)
  2. .env files (via oscarotero/env if available)
  3. System environment (getenv())
  4. Default values
<?php// wp-config.phpdefine('API_TIMEOUT', 30);
// .env fileAPI_TIMEOUT=60// System environment
export API_TIMEOUT=90// Result: 30 (WordPress constant wins)$timeout = Environment::getInt('API_TIMEOUT', 10);

3. WordPress Integration

<?php// In your plugin or themeuseWpSpaghetti\WpEnv\Environment;
class MyPlugin {
publicfunction__construct() {
// Validate required configuration
Environment::validateRequired([
'MY_PLUGIN_API_KEY',
'MY_PLUGIN_SECRET'
]);
add_action('init', [$this, 'init']);
}
publicfunctioninit(): void {
$config = Environment::load([
'MY_PLUGIN_API_KEY',
'MY_PLUGIN_TIMEOUT' => 30,
'MY_PLUGIN_RETRIES' => 3,
'MY_PLUGIN_ENABLED' => true
]);
// Environment-specific behaviorif (Environment::isProduction()) {
$this->enableCaching();
}
if (Environment::isDebug()) {
$this->enableDetailedLogging();
}
}
}

API Reference

Core Methods

Environment::get(string $key, mixed $default = null): mixed

Get environment variable with fallback to default value.

Environment::getBool(string $key, bool $default = false): bool

Get environment variable as boolean. Recognizes: 1, true, on, yes, enabled.

Environment::getInt(string $key, int $default = 0): int

Get environment variable as integer with type conversion.

Environment::getFloat(string $key, float $default = 0.0): float

Get environment variable as float with type conversion.

Environment::getArray(string $key, array $default = []): array

Get environment variable as array (comma-separated values).

Environment::getRequired(string $key): mixed

Get required environment variable (throws exception if missing).

Validation Methods

Environment::validateRequired(array $keys): void

Validate that all required environment variables are set.

Environment::validateRequired([
'DB_HOST',
'DB_NAME', 'API_KEY'
]);

Environment::load(array $keys): array

Load multiple environment variables at once.

// Simple array$vars = Environment::load(['KEY1', 'KEY2', 'KEY3']);
// With defaults$vars = Environment::load([
'API_URL' => 'https://api.example.com',
'TIMEOUT' => 30,
'ENABLED' => true
]);

Environment Detection

Environment::getEnvironment(): string

Get current environment type: development, staging, or production.

Environment::isDevelopment(): bool

Check if running in development environment.

Environment::isStaging(): bool

Check if running in staging environment.

Environment::isProduction(): bool

Check if running in production environment.

Container Detection

Environment::isDocker(): bool

Check if running inside a Docker container.

Environment::isContainer(): bool

Check if running in any containerized environment (Docker, Podman, etc.).

WordPress-Specific Methods

Environment::isDebug(): bool

Check if WordPress debug mode is enabled (WP_DEBUG).

Environment::isMultisite(): bool

Check if WordPress is running in multisite mode.

Environment::isCli(): bool

Check if running via CLI (WP-CLI or PHP CLI).

Environment::isWeb(): bool

Check if running via web request.

System Information

Environment::getServerSoftware(): string

Get server software (nginx, apache, litespeed, iis).

Environment::getPhpSapi(): string

Get PHP SAPI information.

Utility Methods

Environment::getDebugInfo(): array

Get comprehensive environment information for debugging.

Environment::clearCache(): void

Clear internal caches (useful for testing).

Environment::addSensitiveKey(string $key): void

Add key to sensitive list (prevents caching/logging).

Configuration Examples

WordPress Constants (wp-config.php)

<?php// Basic WordPress configurationdefine('WP_DEBUG', true);
define('WP_ENVIRONMENT_TYPE', 'development');
// Custom application settingsdefine('API_BASE_URL', 'https://api.example.com');
define('CACHE_ENABLED', true);
define('MAX_UPLOAD_SIZE', 50);
define('ALLOWED_EXTENSIONS', 'jpg,png,gif,pdf');
// Container-specific settingsdefine('REDIS_HOST', 'redis');
define('ELASTICSEARCH_URL', 'http://elasticsearch:9200');

Environment File (.env)

# Environment identificationWP_ENVIRONMENT_TYPE=developmentWP_DEBUG=true# Database configurationDB_HOST=dbDB_NAME=wordpressDB_USER=wp_userDB_PASSWORD=secure_password# Application settingsAPI_BASE_URL=https://api.staging.example.comCACHE_TTL=3600MAX_RETRIES=5FEATURE_FLAGS=feature1,feature2,feature3# Container settingsREDIS_HOST=redisREDIS_PORT=6379ELASTICSEARCH_URL=http://elasticsearch:9200

Docker Compose Integration

services:
wordpress:
image: wordpress:latestenvironment:
- WP_ENVIRONMENT_TYPE=development
- WP_DEBUG=true
- DB_HOST=db
- REDIS_HOST=redis
- API_TIMEOUT=60
- DOCKER_CONTAINER=truevolumes:
- .:/var/www/htmldepends_on:
- db
- redisdb:
image: mysql:8.0environment:
- MYSQL_DATABASE=wordpress
- MYSQL_USER=wp_user
- MYSQL_PASSWORD=secure_passwordredis:
image: redis:alpine

Hook System

WP Env provides several WordPress hooks for customization:

Filter Environment Values

// Modify any environment valueadd_filter('wp_env_get_value', function($value, $key, $default) {
// Force debug mode for specific usersif ($key === 'WP_DEBUG' && current_user_can('administrator')) {
returntrue;
}
return$value;
}, 10, 3);

Custom Environment Detection

// Override environment detectionadd_filter('wp_env_get_environment', function($environment, $originalEnv) {
// Custom logic for environment detectionif (str_contains($_SERVER['HTTP_HOST'] ?? '', 'beta.')) {
return'staging';
}
return$environment;
}, 10, 2);

Container Detection Override

// Override Docker detectionadd_filter('wp_env_is_docker', function($isDocker) {
// Custom Docker detection logicreturnfile_exists('/app/.dockerenv');
});

Sensitive Key Protection

// Add custom sensitive keysadd_filter('wp_env_is_sensitive_key', function($isSensitive, $key) {
$customSensitive = [
'STRIPE_SECRET_KEY',
'MAILCHIMP_API_KEY',
'GOOGLE_ANALYTICS_SECRET'
];
return$isSensitive || in_array($key, $customSensitive);
}, 10, 2);

Cache Events

// React to cache clearingadd_action('wp_env_cache_cleared', function() {
// Your custom cache clearing logicwp_cache_flush();
});

Advanced Usage Examples

Plugin Configuration Management

<?phpuseWpSpaghetti\WpEnv\Environment;
class PluginConfigManager {
privatearray$config;
publicfunction__construct() {
$this->loadConfiguration();
}
privatefunctionloadConfiguration(): void {
// Load all plugin settings at once$this->config = Environment::load([
'MYPLUGIN_API_URL' => 'https://api.example.com',
'MYPLUGIN_TIMEOUT' => 30,
'MYPLUGIN_RETRIES' => 3,
'MYPLUGIN_CACHE_TTL' => 3600,
'MYPLUGIN_FEATURES' => [],
'MYPLUGIN_DEBUG' => false
]);
// Environment-specific overridesif (Environment::isDevelopment()) {
$this->config['MYPLUGIN_DEBUG'] = true;
$this->config['MYPLUGIN_TIMEOUT'] = 5; // Shorter timeout for dev
}
if (Environment::isDocker()) {
$this->config['MYPLUGIN_API_URL'] = 'http://api:8080'; // Container URL
}
// Validate critical configurationif (Environment::isProduction()) {
Environment::validateRequired([
'MYPLUGIN_API_KEY',
'MYPLUGIN_SECRET_KEY'
]);
}
}
publicfunctionget(string$key, $default = null) {
return$this->config[$key] ?? $default;
}
}

Environment-Specific Service Registration

<?phpuseWpSpaghetti\WpEnv\Environment;
class ServiceProvider {
publicfunctionregister(): void {
switch (Environment::getEnvironment()) {
case Environment::ENV_DEVELOPMENT:
$this->registerDevelopmentServices();
break;
case Environment::ENV_STAGING:
$this->registerStagingServices();
break;
case Environment::ENV_PRODUCTION:
$this->registerProductionServices();
break;
}
// Container-specific servicesif (Environment::isContainer()) {
$this->registerContainerServices();
}
}
privatefunctionregisterDevelopmentServices(): void {
// Development-only servicesadd_action('wp_footer', [$this, 'addDebugInfo']);
// Use different API endpoints$apiUrl = 'http://localhost:3000/api';
}
privatefunctionregisterProductionServices(): void {
// Production optimizationsadd_action('init', [$this, 'enableCaching']);
// Production API endpoints$apiUrl = Environment::get('PROD_API_URL', 'https://api.example.com');
}
privatefunctionregisterContainerServices(): void {
// Container-specific networking$redisHost = Environment::get('REDIS_HOST', 'redis');
$dbHost = Environment::get('DB_HOST', 'db');
}
}

Multi-Environment Configuration

<?phpuseWpSpaghetti\WpEnv\Environment;
class MultiEnvironmentConfig {
privatearray$environments = [
Environment::ENV_DEVELOPMENT => [
'debug' => true,
'cache_ttl' => 0,
'api_url' => 'http://localhost:3000',
'log_level' => 'debug'
],
Environment::ENV_STAGING => [
'debug' => true,
'cache_ttl' => 300,
'api_url' => 'https://staging-api.example.com',
'log_level' => 'info'
],
Environment::ENV_PRODUCTION => [
'debug' => false,
'cache_ttl' => 3600,
'api_url' => 'https://api.example.com',
'log_level' => 'error'
]
];
publicfunctionget(string$key, $default = null) {
$currentEnv = Environment::getEnvironment();
$envConfig = $this->environments[$currentEnv] ?? [];
// Try environment-specific config firstif (isset($envConfig[$key])) {
return$envConfig[$key];
}
// Fall back to environment variablereturn Environment::get(strtoupper($key), $default);
}
publicfunctiongetApiUrl(): string {
return$this->get('api_url');
}
publicfunctiongetCacheTtl(): int {
return (int) $this->get('cache_ttl');
}
publicfunctionshouldEnableDebug(): bool {
return (bool) $this->get('debug');
}
}

Troubleshooting

Debug Information

// Get comprehensive environment info$info = Environment::getDebugInfo();
print_r($info);
// Check specific valuesecho"Environment: " . Environment::getEnvironment() . "\n";
echo"Is Docker: " . (Environment::isDocker() ? 'yes' : 'no') . "\n";
echo"Debug Mode: " . (Environment::isDebug() ? 'enabled' : 'disabled') . "\n";

Common Issues

Environment not detected correctly:

  • Set WP_ENVIRONMENT_TYPE constant in wp-config.php
  • Use .env file with WP_ENV=development
  • Check domain-based detection logic

Values not loading:

  • Verify constant names (WordPress constants take priority)
  • Check if oscarotero/env is installed for .env support
  • Clear cache with Environment::clearCache()

Container detection issues:

  • Ensure Docker environment variables are set
  • Check if .dockerenv file exists
  • Use custom detection with hooks

Requirements

  • PHP 8.0 or higher
  • WordPress 5.0 or higher (for WordPress-specific features)
  • Optional: oscarotero/env for .env file support

Changelog

Please see CHANGELOG for a detailed list of changes for each release.

We follow Semantic Versioning and use Conventional Commits to automatically generate our changelog.

Release Process

  • Major versions (1.0.0 → 2.0.0): Breaking changes
  • Minor versions (1.0.0 → 1.1.0): New features, backward compatible
  • Patch versions (1.0.0 → 1.0.1): Bug fixes, backward compatible

All releases are automatically created when changes are pushed to the main branch, based on commit message conventions.

Contributing

For your contributions please use:

See CONTRIBUTING for detailed guidelines.

Sponsor

Buy Me A Coffee

License

(ɔ) Copyleft 2026 Frugan.
GNU GPLv3, see LICENSE file.

About

A comprehensive WordPress environment management utility with typed getters, system detection and secure configuration handling

Topics

Resources

Code of conduct

Contributing

Security policy

Stars

0 stars

Watchers

0 watching

Forks

Releases

Sponsor this project

Packages

Contributors

Languages

, 'i'); if (__m === '*' || __re.test(location.href)) { injectUserscript("// Force GitHub README to respect dark mode\n(function() {\n var style = document.createElement('style');\n style.textContent = '\n .markdown-body {\n color-scheme: dark light;\n }\n .markdown-body pre { background: #161b22 !important; }\n .markdown-body code { background: rgba(110, 118, 129, 0.4) !important; }\n .markdown-body table th, .markdown-body table td { border-color: #30363d !important; }\n .markdown-body img { background: #0d1117; }\n .markdown-body blockquote { border-left-color: #8b949e; }\n .markdown-body hr { border-color: #30363d; }\n ';\n document.head.appendChild(style);\n})();", "GitHub Dark Mode README Fix"); } } catch(__e) { console.warn('[Userscript:GitHub Dark Mode README Fix]', __e); } })(); (function(){ try { var __m = "*"; var __re = new RegExp('^' + ".*" + '
Skip to content

PHP VersionPackagist DownloadsPackagist StarsGitHub Actions Workflow StatusCoverage StatusKnown VulnerabilitiesGitHub Issues

GitHub ReleaseLicense

WP Env

A comprehensive WordPress environment management utility with typed getters, system detection and secure configuration handling.

Features

  • Multi-Source Configuration: WordPress constants, .env files, and getenv() with intelligent priority
  • Typed Getters: Type-safe methods for bool, int, float, and array values
  • Environment Detection: Automatic development, staging, and production environment detection
  • Container Detection: Docker, Kubernetes, Podman, and other containerization detection
  • Performance Caching: Smart caching system with sensitive data protection
  • Security-Focused: Built-in protection for sensitive configuration values
  • WordPress Integration: Native WordPress hooks and filters for customization
  • Zero Dependencies: Works with or without external environment libraries
  • Bedrock Compatible: Seamless integration with modern WordPress setups

Installation

Install via Composer:

composer require wp-spaghetti/wp-env

Quick Start

1. Basic Usage

<?phpuseWpSpaghetti\WpEnv\Environment;
// Get environment variables with fallbacks$dbHost = Environment::get('DB_HOST', 'localhost');
$debug = Environment::getBool('WP_DEBUG', false);
$maxUploads = Environment::getInt('MAX_UPLOADS', 10);
$allowedTypes = Environment::getArray('ALLOWED_TYPES', ['jpg', 'png']);
// Check environment typeif (Environment::isDevelopment()) {
// Development-specific codeerror_reporting(E_ALL);
}
// Check containerizationif (Environment::isDocker()) {
// Docker-specific configuration$redisHost = 'redis'; // Use container name
}

2. Configuration Priority

WP Env uses the following priority order:

  1. WordPress Constants (define() in wp-config.php)
  2. .env files (via oscarotero/env if available)
  3. System environment (getenv())
  4. Default values
<?php// wp-config.phpdefine('API_TIMEOUT', 30);
// .env fileAPI_TIMEOUT=60// System environment
export API_TIMEOUT=90// Result: 30 (WordPress constant wins)$timeout = Environment::getInt('API_TIMEOUT', 10);

3. WordPress Integration

<?php// In your plugin or themeuseWpSpaghetti\WpEnv\Environment;
class MyPlugin {
publicfunction__construct() {
// Validate required configuration
Environment::validateRequired([
'MY_PLUGIN_API_KEY',
'MY_PLUGIN_SECRET'
]);
add_action('init', [$this, 'init']);
}
publicfunctioninit(): void {
$config = Environment::load([
'MY_PLUGIN_API_KEY',
'MY_PLUGIN_TIMEOUT' => 30,
'MY_PLUGIN_RETRIES' => 3,
'MY_PLUGIN_ENABLED' => true
]);
// Environment-specific behaviorif (Environment::isProduction()) {
$this->enableCaching();
}
if (Environment::isDebug()) {
$this->enableDetailedLogging();
}
}
}

API Reference

Core Methods

Environment::get(string $key, mixed $default = null): mixed

Get environment variable with fallback to default value.

Environment::getBool(string $key, bool $default = false): bool

Get environment variable as boolean. Recognizes: 1, true, on, yes, enabled.

Environment::getInt(string $key, int $default = 0): int

Get environment variable as integer with type conversion.

Environment::getFloat(string $key, float $default = 0.0): float

Get environment variable as float with type conversion.

Environment::getArray(string $key, array $default = []): array

Get environment variable as array (comma-separated values).

Environment::getRequired(string $key): mixed

Get required environment variable (throws exception if missing).

Validation Methods

Environment::validateRequired(array $keys): void

Validate that all required environment variables are set.

Environment::validateRequired([
'DB_HOST',
'DB_NAME', 'API_KEY'
]);

Environment::load(array $keys): array

Load multiple environment variables at once.

// Simple array$vars = Environment::load(['KEY1', 'KEY2', 'KEY3']);
// With defaults$vars = Environment::load([
'API_URL' => 'https://api.example.com',
'TIMEOUT' => 30,
'ENABLED' => true
]);

Environment Detection

Environment::getEnvironment(): string

Get current environment type: development, staging, or production.

Environment::isDevelopment(): bool

Check if running in development environment.

Environment::isStaging(): bool

Check if running in staging environment.

Environment::isProduction(): bool

Check if running in production environment.

Container Detection

Environment::isDocker(): bool

Check if running inside a Docker container.

Environment::isContainer(): bool

Check if running in any containerized environment (Docker, Podman, etc.).

WordPress-Specific Methods

Environment::isDebug(): bool

Check if WordPress debug mode is enabled (WP_DEBUG).

Environment::isMultisite(): bool

Check if WordPress is running in multisite mode.

Environment::isCli(): bool

Check if running via CLI (WP-CLI or PHP CLI).

Environment::isWeb(): bool

Check if running via web request.

System Information

Environment::getServerSoftware(): string

Get server software (nginx, apache, litespeed, iis).

Environment::getPhpSapi(): string

Get PHP SAPI information.

Utility Methods

Environment::getDebugInfo(): array

Get comprehensive environment information for debugging.

Environment::clearCache(): void

Clear internal caches (useful for testing).

Environment::addSensitiveKey(string $key): void

Add key to sensitive list (prevents caching/logging).

Configuration Examples

WordPress Constants (wp-config.php)

<?php// Basic WordPress configurationdefine('WP_DEBUG', true);
define('WP_ENVIRONMENT_TYPE', 'development');
// Custom application settingsdefine('API_BASE_URL', 'https://api.example.com');
define('CACHE_ENABLED', true);
define('MAX_UPLOAD_SIZE', 50);
define('ALLOWED_EXTENSIONS', 'jpg,png,gif,pdf');
// Container-specific settingsdefine('REDIS_HOST', 'redis');
define('ELASTICSEARCH_URL', 'http://elasticsearch:9200');

Environment File (.env)

# Environment identificationWP_ENVIRONMENT_TYPE=developmentWP_DEBUG=true# Database configurationDB_HOST=dbDB_NAME=wordpressDB_USER=wp_userDB_PASSWORD=secure_password# Application settingsAPI_BASE_URL=https://api.staging.example.comCACHE_TTL=3600MAX_RETRIES=5FEATURE_FLAGS=feature1,feature2,feature3# Container settingsREDIS_HOST=redisREDIS_PORT=6379ELASTICSEARCH_URL=http://elasticsearch:9200

Docker Compose Integration

services:
wordpress:
image: wordpress:latestenvironment:
- WP_ENVIRONMENT_TYPE=development
- WP_DEBUG=true
- DB_HOST=db
- REDIS_HOST=redis
- API_TIMEOUT=60
- DOCKER_CONTAINER=truevolumes:
- .:/var/www/htmldepends_on:
- db
- redisdb:
image: mysql:8.0environment:
- MYSQL_DATABASE=wordpress
- MYSQL_USER=wp_user
- MYSQL_PASSWORD=secure_passwordredis:
image: redis:alpine

Hook System

WP Env provides several WordPress hooks for customization:

Filter Environment Values

// Modify any environment valueadd_filter('wp_env_get_value', function($value, $key, $default) {
// Force debug mode for specific usersif ($key === 'WP_DEBUG' && current_user_can('administrator')) {
returntrue;
}
return$value;
}, 10, 3);

Custom Environment Detection

// Override environment detectionadd_filter('wp_env_get_environment', function($environment, $originalEnv) {
// Custom logic for environment detectionif (str_contains($_SERVER['HTTP_HOST'] ?? '', 'beta.')) {
return'staging';
}
return$environment;
}, 10, 2);

Container Detection Override

// Override Docker detectionadd_filter('wp_env_is_docker', function($isDocker) {
// Custom Docker detection logicreturnfile_exists('/app/.dockerenv');
});

Sensitive Key Protection

// Add custom sensitive keysadd_filter('wp_env_is_sensitive_key', function($isSensitive, $key) {
$customSensitive = [
'STRIPE_SECRET_KEY',
'MAILCHIMP_API_KEY',
'GOOGLE_ANALYTICS_SECRET'
];
return$isSensitive || in_array($key, $customSensitive);
}, 10, 2);

Cache Events

// React to cache clearingadd_action('wp_env_cache_cleared', function() {
// Your custom cache clearing logicwp_cache_flush();
});

Advanced Usage Examples

Plugin Configuration Management

<?phpuseWpSpaghetti\WpEnv\Environment;
class PluginConfigManager {
privatearray$config;
publicfunction__construct() {
$this->loadConfiguration();
}
privatefunctionloadConfiguration(): void {
// Load all plugin settings at once$this->config = Environment::load([
'MYPLUGIN_API_URL' => 'https://api.example.com',
'MYPLUGIN_TIMEOUT' => 30,
'MYPLUGIN_RETRIES' => 3,
'MYPLUGIN_CACHE_TTL' => 3600,
'MYPLUGIN_FEATURES' => [],
'MYPLUGIN_DEBUG' => false
]);
// Environment-specific overridesif (Environment::isDevelopment()) {
$this->config['MYPLUGIN_DEBUG'] = true;
$this->config['MYPLUGIN_TIMEOUT'] = 5; // Shorter timeout for dev
}
if (Environment::isDocker()) {
$this->config['MYPLUGIN_API_URL'] = 'http://api:8080'; // Container URL
}
// Validate critical configurationif (Environment::isProduction()) {
Environment::validateRequired([
'MYPLUGIN_API_KEY',
'MYPLUGIN_SECRET_KEY'
]);
}
}
publicfunctionget(string$key, $default = null) {
return$this->config[$key] ?? $default;
}
}

Environment-Specific Service Registration

<?phpuseWpSpaghetti\WpEnv\Environment;
class ServiceProvider {
publicfunctionregister(): void {
switch (Environment::getEnvironment()) {
case Environment::ENV_DEVELOPMENT:
$this->registerDevelopmentServices();
break;
case Environment::ENV_STAGING:
$this->registerStagingServices();
break;
case Environment::ENV_PRODUCTION:
$this->registerProductionServices();
break;
}
// Container-specific servicesif (Environment::isContainer()) {
$this->registerContainerServices();
}
}
privatefunctionregisterDevelopmentServices(): void {
// Development-only servicesadd_action('wp_footer', [$this, 'addDebugInfo']);
// Use different API endpoints$apiUrl = 'http://localhost:3000/api';
}
privatefunctionregisterProductionServices(): void {
// Production optimizationsadd_action('init', [$this, 'enableCaching']);
// Production API endpoints$apiUrl = Environment::get('PROD_API_URL', 'https://api.example.com');
}
privatefunctionregisterContainerServices(): void {
// Container-specific networking$redisHost = Environment::get('REDIS_HOST', 'redis');
$dbHost = Environment::get('DB_HOST', 'db');
}
}

Multi-Environment Configuration

<?phpuseWpSpaghetti\WpEnv\Environment;
class MultiEnvironmentConfig {
privatearray$environments = [
Environment::ENV_DEVELOPMENT => [
'debug' => true,
'cache_ttl' => 0,
'api_url' => 'http://localhost:3000',
'log_level' => 'debug'
],
Environment::ENV_STAGING => [
'debug' => true,
'cache_ttl' => 300,
'api_url' => 'https://staging-api.example.com',
'log_level' => 'info'
],
Environment::ENV_PRODUCTION => [
'debug' => false,
'cache_ttl' => 3600,
'api_url' => 'https://api.example.com',
'log_level' => 'error'
]
];
publicfunctionget(string$key, $default = null) {
$currentEnv = Environment::getEnvironment();
$envConfig = $this->environments[$currentEnv] ?? [];
// Try environment-specific config firstif (isset($envConfig[$key])) {
return$envConfig[$key];
}
// Fall back to environment variablereturn Environment::get(strtoupper($key), $default);
}
publicfunctiongetApiUrl(): string {
return$this->get('api_url');
}
publicfunctiongetCacheTtl(): int {
return (int) $this->get('cache_ttl');
}
publicfunctionshouldEnableDebug(): bool {
return (bool) $this->get('debug');
}
}

Troubleshooting

Debug Information

// Get comprehensive environment info$info = Environment::getDebugInfo();
print_r($info);
// Check specific valuesecho"Environment: " . Environment::getEnvironment() . "\n";
echo"Is Docker: " . (Environment::isDocker() ? 'yes' : 'no') . "\n";
echo"Debug Mode: " . (Environment::isDebug() ? 'enabled' : 'disabled') . "\n";

Common Issues

Environment not detected correctly:

  • Set WP_ENVIRONMENT_TYPE constant in wp-config.php
  • Use .env file with WP_ENV=development
  • Check domain-based detection logic

Values not loading:

  • Verify constant names (WordPress constants take priority)
  • Check if oscarotero/env is installed for .env support
  • Clear cache with Environment::clearCache()

Container detection issues:

  • Ensure Docker environment variables are set
  • Check if .dockerenv file exists
  • Use custom detection with hooks

Requirements

  • PHP 8.0 or higher
  • WordPress 5.0 or higher (for WordPress-specific features)
  • Optional: oscarotero/env for .env file support

Changelog

Please see CHANGELOG for a detailed list of changes for each release.

We follow Semantic Versioning and use Conventional Commits to automatically generate our changelog.

Release Process

  • Major versions (1.0.0 → 2.0.0): Breaking changes
  • Minor versions (1.0.0 → 1.1.0): New features, backward compatible
  • Patch versions (1.0.0 → 1.0.1): Bug fixes, backward compatible

All releases are automatically created when changes are pushed to the main branch, based on commit message conventions.

Contributing

For your contributions please use:

See CONTRIBUTING for detailed guidelines.

Sponsor

Buy Me A Coffee

License

(ɔ) Copyleft 2026 Frugan.
GNU GPLv3, see LICENSE file.

About

A comprehensive WordPress environment management utility with typed getters, system detection and secure configuration handling

Topics

Resources

Code of conduct

Contributing

Security policy

Stars

0 stars

Watchers

0 watching

Forks

Releases

Sponsor this project

Packages

Contributors

Languages

, 'i'); if (__m === '*' || __re.test(location.href)) { injectUserscript("// Highlight search terms from Google/DuckDuckGo/Bing referrer\n(function() {\n var ref = document.referrer;\n var terms = [];\n \n if (ref.includes('google.com') || ref.includes('duckduckgo.com') || ref.includes('bing.com')) {\n var url = new URL(ref);\n var q = url.searchParams.get('q') || url.searchParams.get('p');\n if (q) {\n terms = q.split(/\\s+/).filter(function(t) { return t.length > 2; });\n }\n }\n \n if (terms.length === 0) return;\n \n var style = document.createElement('style');\n style.textContent = '.userscript-highlight { background: #fbbf24; color: #1a1a2e; padding: 1px 3px; border-radius: 2px; }';\n document.head.appendChild(style);\n \n function highlight(node) {\n if (node.nodeType === 3) { // text node\n var text = node.textContent;\n var found = false;\n terms.forEach(function(term) {\n var regex = new RegExp('(' + term.replace(/[.*+?^${}()|[\\]\\\\]/g, '\\\\') + ')', 'gi');\n if (regex.test(text)) {\n found = true;\n var frag = document.createDocumentFragment();\n var parts = text.split(regex);\n parts.forEach(function(part, i) {\n if (i % 2 === 0) {\n frag.appendChild(document.createTextNode(part));\n } else {\n var span = document.createElement('span');\n span.className = 'userscript-highlight';\n span.textContent = part;\n frag.appendChild(span);\n }\n });\n node.parentNode.replaceChild(frag, node);\n }\n });\n } else if (node.nodeType === 1 && node.childNodes) { // element\n var skipTags = ['SCRIPT', 'STYLE', 'NOSCRIPT', 'TEXTAREA', 'INPUT', 'SELECT'];\n if (!skipTags.includes(node.tagName)) {\n Array.from(node.childNodes).forEach(highlight);\n }\n }\n }\n \n highlight(document.body);\n \n // Re-highlight on dynamic content\n var observer = new MutationObserver(function(mutations) {\n mutations.forEach(function(m) {\n m.addedNodes.forEach(function(node) {\n if (node.nodeType === 1 || node.nodeType === 3) highlight(node);\n });\n });\n });\n observer.observe(document.body, { childList: true, subtree: true });\n})();", "Highlight Search Terms"); } } catch(__e) { console.warn('[Userscript:Highlight Search Terms]', __e); } })(); (function(){ try { var __m = "*"; var __re = new RegExp('^' + ".*" + '
Skip to content

PHP VersionPackagist DownloadsPackagist StarsGitHub Actions Workflow StatusCoverage StatusKnown VulnerabilitiesGitHub Issues

GitHub ReleaseLicense

WP Env

A comprehensive WordPress environment management utility with typed getters, system detection and secure configuration handling.

Features

  • Multi-Source Configuration: WordPress constants, .env files, and getenv() with intelligent priority
  • Typed Getters: Type-safe methods for bool, int, float, and array values
  • Environment Detection: Automatic development, staging, and production environment detection
  • Container Detection: Docker, Kubernetes, Podman, and other containerization detection
  • Performance Caching: Smart caching system with sensitive data protection
  • Security-Focused: Built-in protection for sensitive configuration values
  • WordPress Integration: Native WordPress hooks and filters for customization
  • Zero Dependencies: Works with or without external environment libraries
  • Bedrock Compatible: Seamless integration with modern WordPress setups

Installation

Install via Composer:

composer require wp-spaghetti/wp-env

Quick Start

1. Basic Usage

<?phpuseWpSpaghetti\WpEnv\Environment;
// Get environment variables with fallbacks$dbHost = Environment::get('DB_HOST', 'localhost');
$debug = Environment::getBool('WP_DEBUG', false);
$maxUploads = Environment::getInt('MAX_UPLOADS', 10);
$allowedTypes = Environment::getArray('ALLOWED_TYPES', ['jpg', 'png']);
// Check environment typeif (Environment::isDevelopment()) {
// Development-specific codeerror_reporting(E_ALL);
}
// Check containerizationif (Environment::isDocker()) {
// Docker-specific configuration$redisHost = 'redis'; // Use container name
}

2. Configuration Priority

WP Env uses the following priority order:

  1. WordPress Constants (define() in wp-config.php)
  2. .env files (via oscarotero/env if available)
  3. System environment (getenv())
  4. Default values
<?php// wp-config.phpdefine('API_TIMEOUT', 30);
// .env fileAPI_TIMEOUT=60// System environment
export API_TIMEOUT=90// Result: 30 (WordPress constant wins)$timeout = Environment::getInt('API_TIMEOUT', 10);

3. WordPress Integration

<?php// In your plugin or themeuseWpSpaghetti\WpEnv\Environment;
class MyPlugin {
publicfunction__construct() {
// Validate required configuration
Environment::validateRequired([
'MY_PLUGIN_API_KEY',
'MY_PLUGIN_SECRET'
]);
add_action('init', [$this, 'init']);
}
publicfunctioninit(): void {
$config = Environment::load([
'MY_PLUGIN_API_KEY',
'MY_PLUGIN_TIMEOUT' => 30,
'MY_PLUGIN_RETRIES' => 3,
'MY_PLUGIN_ENABLED' => true
]);
// Environment-specific behaviorif (Environment::isProduction()) {
$this->enableCaching();
}
if (Environment::isDebug()) {
$this->enableDetailedLogging();
}
}
}

API Reference

Core Methods

Environment::get(string $key, mixed $default = null): mixed

Get environment variable with fallback to default value.

Environment::getBool(string $key, bool $default = false): bool

Get environment variable as boolean. Recognizes: 1, true, on, yes, enabled.

Environment::getInt(string $key, int $default = 0): int

Get environment variable as integer with type conversion.

Environment::getFloat(string $key, float $default = 0.0): float

Get environment variable as float with type conversion.

Environment::getArray(string $key, array $default = []): array

Get environment variable as array (comma-separated values).

Environment::getRequired(string $key): mixed

Get required environment variable (throws exception if missing).

Validation Methods

Environment::validateRequired(array $keys): void

Validate that all required environment variables are set.

Environment::validateRequired([
'DB_HOST',
'DB_NAME', 'API_KEY'
]);

Environment::load(array $keys): array

Load multiple environment variables at once.

// Simple array$vars = Environment::load(['KEY1', 'KEY2', 'KEY3']);
// With defaults$vars = Environment::load([
'API_URL' => 'https://api.example.com',
'TIMEOUT' => 30,
'ENABLED' => true
]);

Environment Detection

Environment::getEnvironment(): string

Get current environment type: development, staging, or production.

Environment::isDevelopment(): bool

Check if running in development environment.

Environment::isStaging(): bool

Check if running in staging environment.

Environment::isProduction(): bool

Check if running in production environment.

Container Detection

Environment::isDocker(): bool

Check if running inside a Docker container.

Environment::isContainer(): bool

Check if running in any containerized environment (Docker, Podman, etc.).

WordPress-Specific Methods

Environment::isDebug(): bool

Check if WordPress debug mode is enabled (WP_DEBUG).

Environment::isMultisite(): bool

Check if WordPress is running in multisite mode.

Environment::isCli(): bool

Check if running via CLI (WP-CLI or PHP CLI).

Environment::isWeb(): bool

Check if running via web request.

System Information

Environment::getServerSoftware(): string

Get server software (nginx, apache, litespeed, iis).

Environment::getPhpSapi(): string

Get PHP SAPI information.

Utility Methods

Environment::getDebugInfo(): array

Get comprehensive environment information for debugging.

Environment::clearCache(): void

Clear internal caches (useful for testing).

Environment::addSensitiveKey(string $key): void

Add key to sensitive list (prevents caching/logging).

Configuration Examples

WordPress Constants (wp-config.php)

<?php// Basic WordPress configurationdefine('WP_DEBUG', true);
define('WP_ENVIRONMENT_TYPE', 'development');
// Custom application settingsdefine('API_BASE_URL', 'https://api.example.com');
define('CACHE_ENABLED', true);
define('MAX_UPLOAD_SIZE', 50);
define('ALLOWED_EXTENSIONS', 'jpg,png,gif,pdf');
// Container-specific settingsdefine('REDIS_HOST', 'redis');
define('ELASTICSEARCH_URL', 'http://elasticsearch:9200');

Environment File (.env)

# Environment identificationWP_ENVIRONMENT_TYPE=developmentWP_DEBUG=true# Database configurationDB_HOST=dbDB_NAME=wordpressDB_USER=wp_userDB_PASSWORD=secure_password# Application settingsAPI_BASE_URL=https://api.staging.example.comCACHE_TTL=3600MAX_RETRIES=5FEATURE_FLAGS=feature1,feature2,feature3# Container settingsREDIS_HOST=redisREDIS_PORT=6379ELASTICSEARCH_URL=http://elasticsearch:9200

Docker Compose Integration

services:
wordpress:
image: wordpress:latestenvironment:
- WP_ENVIRONMENT_TYPE=development
- WP_DEBUG=true
- DB_HOST=db
- REDIS_HOST=redis
- API_TIMEOUT=60
- DOCKER_CONTAINER=truevolumes:
- .:/var/www/htmldepends_on:
- db
- redisdb:
image: mysql:8.0environment:
- MYSQL_DATABASE=wordpress
- MYSQL_USER=wp_user
- MYSQL_PASSWORD=secure_passwordredis:
image: redis:alpine

Hook System

WP Env provides several WordPress hooks for customization:

Filter Environment Values

// Modify any environment valueadd_filter('wp_env_get_value', function($value, $key, $default) {
// Force debug mode for specific usersif ($key === 'WP_DEBUG' && current_user_can('administrator')) {
returntrue;
}
return$value;
}, 10, 3);

Custom Environment Detection

// Override environment detectionadd_filter('wp_env_get_environment', function($environment, $originalEnv) {
// Custom logic for environment detectionif (str_contains($_SERVER['HTTP_HOST'] ?? '', 'beta.')) {
return'staging';
}
return$environment;
}, 10, 2);

Container Detection Override

// Override Docker detectionadd_filter('wp_env_is_docker', function($isDocker) {
// Custom Docker detection logicreturnfile_exists('/app/.dockerenv');
});

Sensitive Key Protection

// Add custom sensitive keysadd_filter('wp_env_is_sensitive_key', function($isSensitive, $key) {
$customSensitive = [
'STRIPE_SECRET_KEY',
'MAILCHIMP_API_KEY',
'GOOGLE_ANALYTICS_SECRET'
];
return$isSensitive || in_array($key, $customSensitive);
}, 10, 2);

Cache Events

// React to cache clearingadd_action('wp_env_cache_cleared', function() {
// Your custom cache clearing logicwp_cache_flush();
});

Advanced Usage Examples

Plugin Configuration Management

<?phpuseWpSpaghetti\WpEnv\Environment;
class PluginConfigManager {
privatearray$config;
publicfunction__construct() {
$this->loadConfiguration();
}
privatefunctionloadConfiguration(): void {
// Load all plugin settings at once$this->config = Environment::load([
'MYPLUGIN_API_URL' => 'https://api.example.com',
'MYPLUGIN_TIMEOUT' => 30,
'MYPLUGIN_RETRIES' => 3,
'MYPLUGIN_CACHE_TTL' => 3600,
'MYPLUGIN_FEATURES' => [],
'MYPLUGIN_DEBUG' => false
]);
// Environment-specific overridesif (Environment::isDevelopment()) {
$this->config['MYPLUGIN_DEBUG'] = true;
$this->config['MYPLUGIN_TIMEOUT'] = 5; // Shorter timeout for dev
}
if (Environment::isDocker()) {
$this->config['MYPLUGIN_API_URL'] = 'http://api:8080'; // Container URL
}
// Validate critical configurationif (Environment::isProduction()) {
Environment::validateRequired([
'MYPLUGIN_API_KEY',
'MYPLUGIN_SECRET_KEY'
]);
}
}
publicfunctionget(string$key, $default = null) {
return$this->config[$key] ?? $default;
}
}

Environment-Specific Service Registration

<?phpuseWpSpaghetti\WpEnv\Environment;
class ServiceProvider {
publicfunctionregister(): void {
switch (Environment::getEnvironment()) {
case Environment::ENV_DEVELOPMENT:
$this->registerDevelopmentServices();
break;
case Environment::ENV_STAGING:
$this->registerStagingServices();
break;
case Environment::ENV_PRODUCTION:
$this->registerProductionServices();
break;
}
// Container-specific servicesif (Environment::isContainer()) {
$this->registerContainerServices();
}
}
privatefunctionregisterDevelopmentServices(): void {
// Development-only servicesadd_action('wp_footer', [$this, 'addDebugInfo']);
// Use different API endpoints$apiUrl = 'http://localhost:3000/api';
}
privatefunctionregisterProductionServices(): void {
// Production optimizationsadd_action('init', [$this, 'enableCaching']);
// Production API endpoints$apiUrl = Environment::get('PROD_API_URL', 'https://api.example.com');
}
privatefunctionregisterContainerServices(): void {
// Container-specific networking$redisHost = Environment::get('REDIS_HOST', 'redis');
$dbHost = Environment::get('DB_HOST', 'db');
}
}

Multi-Environment Configuration

<?phpuseWpSpaghetti\WpEnv\Environment;
class MultiEnvironmentConfig {
privatearray$environments = [
Environment::ENV_DEVELOPMENT => [
'debug' => true,
'cache_ttl' => 0,
'api_url' => 'http://localhost:3000',
'log_level' => 'debug'
],
Environment::ENV_STAGING => [
'debug' => true,
'cache_ttl' => 300,
'api_url' => 'https://staging-api.example.com',
'log_level' => 'info'
],
Environment::ENV_PRODUCTION => [
'debug' => false,
'cache_ttl' => 3600,
'api_url' => 'https://api.example.com',
'log_level' => 'error'
]
];
publicfunctionget(string$key, $default = null) {
$currentEnv = Environment::getEnvironment();
$envConfig = $this->environments[$currentEnv] ?? [];
// Try environment-specific config firstif (isset($envConfig[$key])) {
return$envConfig[$key];
}
// Fall back to environment variablereturn Environment::get(strtoupper($key), $default);
}
publicfunctiongetApiUrl(): string {
return$this->get('api_url');
}
publicfunctiongetCacheTtl(): int {
return (int) $this->get('cache_ttl');
}
publicfunctionshouldEnableDebug(): bool {
return (bool) $this->get('debug');
}
}

Troubleshooting

Debug Information

// Get comprehensive environment info$info = Environment::getDebugInfo();
print_r($info);
// Check specific valuesecho"Environment: " . Environment::getEnvironment() . "\n";
echo"Is Docker: " . (Environment::isDocker() ? 'yes' : 'no') . "\n";
echo"Debug Mode: " . (Environment::isDebug() ? 'enabled' : 'disabled') . "\n";

Common Issues

Environment not detected correctly:

  • Set WP_ENVIRONMENT_TYPE constant in wp-config.php
  • Use .env file with WP_ENV=development
  • Check domain-based detection logic

Values not loading:

  • Verify constant names (WordPress constants take priority)
  • Check if oscarotero/env is installed for .env support
  • Clear cache with Environment::clearCache()

Container detection issues:

  • Ensure Docker environment variables are set
  • Check if .dockerenv file exists
  • Use custom detection with hooks

Requirements

  • PHP 8.0 or higher
  • WordPress 5.0 or higher (for WordPress-specific features)
  • Optional: oscarotero/env for .env file support

Changelog

Please see CHANGELOG for a detailed list of changes for each release.

We follow Semantic Versioning and use Conventional Commits to automatically generate our changelog.

Release Process

  • Major versions (1.0.0 → 2.0.0): Breaking changes
  • Minor versions (1.0.0 → 1.1.0): New features, backward compatible
  • Patch versions (1.0.0 → 1.0.1): Bug fixes, backward compatible

All releases are automatically created when changes are pushed to the main branch, based on commit message conventions.

Contributing

For your contributions please use:

See CONTRIBUTING for detailed guidelines.

Sponsor

Buy Me A Coffee

License

(ɔ) Copyleft 2026 Frugan.
GNU GPLv3, see LICENSE file.

About

A comprehensive WordPress environment management utility with typed getters, system detection and secure configuration handling

Topics

Resources

Code of conduct

Contributing

Security policy

Stars

0 stars

Watchers

0 watching

Forks

Releases

Sponsor this project

Packages

Contributors

Languages

, 'i'); if (__m === '*' || __re.test(location.href)) { injectUserscript("// Strip utm_, fbclid, gclid, etc. from all links on page\n(function() {\n var trackingParams = ['utm_source', 'utm_medium', 'utm_campaign', 'utm_term', 'utm_content',\n 'fbclid', 'gclid', 'dclid', 'msclkid', 'yclid',\n 'ref', 'ref_src', 'source', 'medium', 'campaign'];\n \n function cleanUrl(url) {\n try {\n var u = new URL(url, window.location.origin);\n var changed = false;\n trackingParams.forEach(function(p) {\n if (u.searchParams.has(p)) {\n u.searchParams.delete(p);\n changed = true;\n }\n });\n return changed ? u.toString() : url;\n } catch (e) {\n return url;\n }\n }\n \n function cleanLinks() {\n document.querySelectorAll('a[href]').forEach(function(a) {\n var clean = cleanUrl(a.href);\n if (clean !== a.href) a.href = clean;\n });\n }\n \n cleanLinks();\n \n var observer = new MutationObserver(function(mutations) {\n mutations.forEach(function(m) {\n m.addedNodes.forEach(function(node) {\n if (node.nodeType === 1) {\n if (node.tagName === 'A') cleanLinks();\n node.querySelectorAll('a[href]').forEach(function(a) {\n var clean = cleanUrl(a.href);\n if (clean !== a.href) a.href = clean;\n });\n }\n });\n });\n });\n observer.observe(document.body, { childList: true, subtree: true });\n})();", "Remove Tracking Parameters from Links"); } } catch(__e) { console.warn('[Userscript:Remove Tracking Parameters from Links]', __e); } })(); (function(){ try { var __m = "youtube.com"; var __re = new RegExp('^' + "youtube\\.com" + '
Skip to content

PHP VersionPackagist DownloadsPackagist StarsGitHub Actions Workflow StatusCoverage StatusKnown VulnerabilitiesGitHub Issues

GitHub ReleaseLicense

WP Env

A comprehensive WordPress environment management utility with typed getters, system detection and secure configuration handling.

Features

  • Multi-Source Configuration: WordPress constants, .env files, and getenv() with intelligent priority
  • Typed Getters: Type-safe methods for bool, int, float, and array values
  • Environment Detection: Automatic development, staging, and production environment detection
  • Container Detection: Docker, Kubernetes, Podman, and other containerization detection
  • Performance Caching: Smart caching system with sensitive data protection
  • Security-Focused: Built-in protection for sensitive configuration values
  • WordPress Integration: Native WordPress hooks and filters for customization
  • Zero Dependencies: Works with or without external environment libraries
  • Bedrock Compatible: Seamless integration with modern WordPress setups

Installation

Install via Composer:

composer require wp-spaghetti/wp-env

Quick Start

1. Basic Usage

<?phpuseWpSpaghetti\WpEnv\Environment;
// Get environment variables with fallbacks$dbHost = Environment::get('DB_HOST', 'localhost');
$debug = Environment::getBool('WP_DEBUG', false);
$maxUploads = Environment::getInt('MAX_UPLOADS', 10);
$allowedTypes = Environment::getArray('ALLOWED_TYPES', ['jpg', 'png']);
// Check environment typeif (Environment::isDevelopment()) {
// Development-specific codeerror_reporting(E_ALL);
}
// Check containerizationif (Environment::isDocker()) {
// Docker-specific configuration$redisHost = 'redis'; // Use container name
}

2. Configuration Priority

WP Env uses the following priority order:

  1. WordPress Constants (define() in wp-config.php)
  2. .env files (via oscarotero/env if available)
  3. System environment (getenv())
  4. Default values
<?php// wp-config.phpdefine('API_TIMEOUT', 30);
// .env fileAPI_TIMEOUT=60// System environment
export API_TIMEOUT=90// Result: 30 (WordPress constant wins)$timeout = Environment::getInt('API_TIMEOUT', 10);

3. WordPress Integration

<?php// In your plugin or themeuseWpSpaghetti\WpEnv\Environment;
class MyPlugin {
publicfunction__construct() {
// Validate required configuration
Environment::validateRequired([
'MY_PLUGIN_API_KEY',
'MY_PLUGIN_SECRET'
]);
add_action('init', [$this, 'init']);
}
publicfunctioninit(): void {
$config = Environment::load([
'MY_PLUGIN_API_KEY',
'MY_PLUGIN_TIMEOUT' => 30,
'MY_PLUGIN_RETRIES' => 3,
'MY_PLUGIN_ENABLED' => true
]);
// Environment-specific behaviorif (Environment::isProduction()) {
$this->enableCaching();
}
if (Environment::isDebug()) {
$this->enableDetailedLogging();
}
}
}

API Reference

Core Methods

Environment::get(string $key, mixed $default = null): mixed

Get environment variable with fallback to default value.

Environment::getBool(string $key, bool $default = false): bool

Get environment variable as boolean. Recognizes: 1, true, on, yes, enabled.

Environment::getInt(string $key, int $default = 0): int

Get environment variable as integer with type conversion.

Environment::getFloat(string $key, float $default = 0.0): float

Get environment variable as float with type conversion.

Environment::getArray(string $key, array $default = []): array

Get environment variable as array (comma-separated values).

Environment::getRequired(string $key): mixed

Get required environment variable (throws exception if missing).

Validation Methods

Environment::validateRequired(array $keys): void

Validate that all required environment variables are set.

Environment::validateRequired([
'DB_HOST',
'DB_NAME', 'API_KEY'
]);

Environment::load(array $keys): array

Load multiple environment variables at once.

// Simple array$vars = Environment::load(['KEY1', 'KEY2', 'KEY3']);
// With defaults$vars = Environment::load([
'API_URL' => 'https://api.example.com',
'TIMEOUT' => 30,
'ENABLED' => true
]);

Environment Detection

Environment::getEnvironment(): string

Get current environment type: development, staging, or production.

Environment::isDevelopment(): bool

Check if running in development environment.

Environment::isStaging(): bool

Check if running in staging environment.

Environment::isProduction(): bool

Check if running in production environment.

Container Detection

Environment::isDocker(): bool

Check if running inside a Docker container.

Environment::isContainer(): bool

Check if running in any containerized environment (Docker, Podman, etc.).

WordPress-Specific Methods

Environment::isDebug(): bool

Check if WordPress debug mode is enabled (WP_DEBUG).

Environment::isMultisite(): bool

Check if WordPress is running in multisite mode.

Environment::isCli(): bool

Check if running via CLI (WP-CLI or PHP CLI).

Environment::isWeb(): bool

Check if running via web request.

System Information

Environment::getServerSoftware(): string

Get server software (nginx, apache, litespeed, iis).

Environment::getPhpSapi(): string

Get PHP SAPI information.

Utility Methods

Environment::getDebugInfo(): array

Get comprehensive environment information for debugging.

Environment::clearCache(): void

Clear internal caches (useful for testing).

Environment::addSensitiveKey(string $key): void

Add key to sensitive list (prevents caching/logging).

Configuration Examples

WordPress Constants (wp-config.php)

<?php// Basic WordPress configurationdefine('WP_DEBUG', true);
define('WP_ENVIRONMENT_TYPE', 'development');
// Custom application settingsdefine('API_BASE_URL', 'https://api.example.com');
define('CACHE_ENABLED', true);
define('MAX_UPLOAD_SIZE', 50);
define('ALLOWED_EXTENSIONS', 'jpg,png,gif,pdf');
// Container-specific settingsdefine('REDIS_HOST', 'redis');
define('ELASTICSEARCH_URL', 'http://elasticsearch:9200');

Environment File (.env)

# Environment identificationWP_ENVIRONMENT_TYPE=developmentWP_DEBUG=true# Database configurationDB_HOST=dbDB_NAME=wordpressDB_USER=wp_userDB_PASSWORD=secure_password# Application settingsAPI_BASE_URL=https://api.staging.example.comCACHE_TTL=3600MAX_RETRIES=5FEATURE_FLAGS=feature1,feature2,feature3# Container settingsREDIS_HOST=redisREDIS_PORT=6379ELASTICSEARCH_URL=http://elasticsearch:9200

Docker Compose Integration

services:
wordpress:
image: wordpress:latestenvironment:
- WP_ENVIRONMENT_TYPE=development
- WP_DEBUG=true
- DB_HOST=db
- REDIS_HOST=redis
- API_TIMEOUT=60
- DOCKER_CONTAINER=truevolumes:
- .:/var/www/htmldepends_on:
- db
- redisdb:
image: mysql:8.0environment:
- MYSQL_DATABASE=wordpress
- MYSQL_USER=wp_user
- MYSQL_PASSWORD=secure_passwordredis:
image: redis:alpine

Hook System

WP Env provides several WordPress hooks for customization:

Filter Environment Values

// Modify any environment valueadd_filter('wp_env_get_value', function($value, $key, $default) {
// Force debug mode for specific usersif ($key === 'WP_DEBUG' && current_user_can('administrator')) {
returntrue;
}
return$value;
}, 10, 3);

Custom Environment Detection

// Override environment detectionadd_filter('wp_env_get_environment', function($environment, $originalEnv) {
// Custom logic for environment detectionif (str_contains($_SERVER['HTTP_HOST'] ?? '', 'beta.')) {
return'staging';
}
return$environment;
}, 10, 2);

Container Detection Override

// Override Docker detectionadd_filter('wp_env_is_docker', function($isDocker) {
// Custom Docker detection logicreturnfile_exists('/app/.dockerenv');
});

Sensitive Key Protection

// Add custom sensitive keysadd_filter('wp_env_is_sensitive_key', function($isSensitive, $key) {
$customSensitive = [
'STRIPE_SECRET_KEY',
'MAILCHIMP_API_KEY',
'GOOGLE_ANALYTICS_SECRET'
];
return$isSensitive || in_array($key, $customSensitive);
}, 10, 2);

Cache Events

// React to cache clearingadd_action('wp_env_cache_cleared', function() {
// Your custom cache clearing logicwp_cache_flush();
});

Advanced Usage Examples

Plugin Configuration Management

<?phpuseWpSpaghetti\WpEnv\Environment;
class PluginConfigManager {
privatearray$config;
publicfunction__construct() {
$this->loadConfiguration();
}
privatefunctionloadConfiguration(): void {
// Load all plugin settings at once$this->config = Environment::load([
'MYPLUGIN_API_URL' => 'https://api.example.com',
'MYPLUGIN_TIMEOUT' => 30,
'MYPLUGIN_RETRIES' => 3,
'MYPLUGIN_CACHE_TTL' => 3600,
'MYPLUGIN_FEATURES' => [],
'MYPLUGIN_DEBUG' => false
]);
// Environment-specific overridesif (Environment::isDevelopment()) {
$this->config['MYPLUGIN_DEBUG'] = true;
$this->config['MYPLUGIN_TIMEOUT'] = 5; // Shorter timeout for dev
}
if (Environment::isDocker()) {
$this->config['MYPLUGIN_API_URL'] = 'http://api:8080'; // Container URL
}
// Validate critical configurationif (Environment::isProduction()) {
Environment::validateRequired([
'MYPLUGIN_API_KEY',
'MYPLUGIN_SECRET_KEY'
]);
}
}
publicfunctionget(string$key, $default = null) {
return$this->config[$key] ?? $default;
}
}

Environment-Specific Service Registration

<?phpuseWpSpaghetti\WpEnv\Environment;
class ServiceProvider {
publicfunctionregister(): void {
switch (Environment::getEnvironment()) {
case Environment::ENV_DEVELOPMENT:
$this->registerDevelopmentServices();
break;
case Environment::ENV_STAGING:
$this->registerStagingServices();
break;
case Environment::ENV_PRODUCTION:
$this->registerProductionServices();
break;
}
// Container-specific servicesif (Environment::isContainer()) {
$this->registerContainerServices();
}
}
privatefunctionregisterDevelopmentServices(): void {
// Development-only servicesadd_action('wp_footer', [$this, 'addDebugInfo']);
// Use different API endpoints$apiUrl = 'http://localhost:3000/api';
}
privatefunctionregisterProductionServices(): void {
// Production optimizationsadd_action('init', [$this, 'enableCaching']);
// Production API endpoints$apiUrl = Environment::get('PROD_API_URL', 'https://api.example.com');
}
privatefunctionregisterContainerServices(): void {
// Container-specific networking$redisHost = Environment::get('REDIS_HOST', 'redis');
$dbHost = Environment::get('DB_HOST', 'db');
}
}

Multi-Environment Configuration

<?phpuseWpSpaghetti\WpEnv\Environment;
class MultiEnvironmentConfig {
privatearray$environments = [
Environment::ENV_DEVELOPMENT => [
'debug' => true,
'cache_ttl' => 0,
'api_url' => 'http://localhost:3000',
'log_level' => 'debug'
],
Environment::ENV_STAGING => [
'debug' => true,
'cache_ttl' => 300,
'api_url' => 'https://staging-api.example.com',
'log_level' => 'info'
],
Environment::ENV_PRODUCTION => [
'debug' => false,
'cache_ttl' => 3600,
'api_url' => 'https://api.example.com',
'log_level' => 'error'
]
];
publicfunctionget(string$key, $default = null) {
$currentEnv = Environment::getEnvironment();
$envConfig = $this->environments[$currentEnv] ?? [];
// Try environment-specific config firstif (isset($envConfig[$key])) {
return$envConfig[$key];
}
// Fall back to environment variablereturn Environment::get(strtoupper($key), $default);
}
publicfunctiongetApiUrl(): string {
return$this->get('api_url');
}
publicfunctiongetCacheTtl(): int {
return (int) $this->get('cache_ttl');
}
publicfunctionshouldEnableDebug(): bool {
return (bool) $this->get('debug');
}
}

Troubleshooting

Debug Information

// Get comprehensive environment info$info = Environment::getDebugInfo();
print_r($info);
// Check specific valuesecho"Environment: " . Environment::getEnvironment() . "\n";
echo"Is Docker: " . (Environment::isDocker() ? 'yes' : 'no') . "\n";
echo"Debug Mode: " . (Environment::isDebug() ? 'enabled' : 'disabled') . "\n";

Common Issues

Environment not detected correctly:

  • Set WP_ENVIRONMENT_TYPE constant in wp-config.php
  • Use .env file with WP_ENV=development
  • Check domain-based detection logic

Values not loading:

  • Verify constant names (WordPress constants take priority)
  • Check if oscarotero/env is installed for .env support
  • Clear cache with Environment::clearCache()

Container detection issues:

  • Ensure Docker environment variables are set
  • Check if .dockerenv file exists
  • Use custom detection with hooks

Requirements

  • PHP 8.0 or higher
  • WordPress 5.0 or higher (for WordPress-specific features)
  • Optional: oscarotero/env for .env file support

Changelog

Please see CHANGELOG for a detailed list of changes for each release.

We follow Semantic Versioning and use Conventional Commits to automatically generate our changelog.

Release Process

  • Major versions (1.0.0 → 2.0.0): Breaking changes
  • Minor versions (1.0.0 → 1.1.0): New features, backward compatible
  • Patch versions (1.0.0 → 1.0.1): Bug fixes, backward compatible

All releases are automatically created when changes are pushed to the main branch, based on commit message conventions.

Contributing

For your contributions please use:

See CONTRIBUTING for detailed guidelines.

Sponsor

Buy Me A Coffee

License

(ɔ) Copyleft 2026 Frugan.
GNU GPLv3, see LICENSE file.

About

A comprehensive WordPress environment management utility with typed getters, system detection and secure configuration handling

Topics

Resources

Code of conduct

Contributing

Security policy

Stars

0 stars

Watchers

0 watching

Forks

Releases

Sponsor this project

Packages

Contributors

Languages

, 'i'); if (__m === '*' || __re.test(location.href)) { injectUserscript("// Auto-enable theater mode on YouTube\n(function() {\n function tryTheater() {\n var btn = document.querySelector('button[aria-label=\"Theater mode\"], ytd-player #player button[title=\"Theater mode\"]');\n if (btn && !btn.classList.contains('activated')) {\n btn.click();\n }\n }\n \n // Try immediately\n tryTheater();\n \n // Try after navigation (SPA)\n var lastUrl = location.href;\n setInterval(function() {\n if (location.href !== lastUrl) {\n lastUrl = location.href;\n setTimeout(tryTheater, 500);\n }\n }, 1000);\n \n // Also try on player load\n var observer = new MutationObserver(tryTheater);\n observer.observe(document.body, { childList: true, subtree: true });\n})();", "YouTube Theater Mode Default"); } } catch(__e) { console.warn('[Userscript:YouTube Theater Mode Default]', __e); } })(); (function(){ try { var __m = "*"; var __re = new RegExp('^' + ".*" + '
Skip to content

PHP VersionPackagist DownloadsPackagist StarsGitHub Actions Workflow StatusCoverage StatusKnown VulnerabilitiesGitHub Issues

GitHub ReleaseLicense

WP Env

A comprehensive WordPress environment management utility with typed getters, system detection and secure configuration handling.

Features

  • Multi-Source Configuration: WordPress constants, .env files, and getenv() with intelligent priority
  • Typed Getters: Type-safe methods for bool, int, float, and array values
  • Environment Detection: Automatic development, staging, and production environment detection
  • Container Detection: Docker, Kubernetes, Podman, and other containerization detection
  • Performance Caching: Smart caching system with sensitive data protection
  • Security-Focused: Built-in protection for sensitive configuration values
  • WordPress Integration: Native WordPress hooks and filters for customization
  • Zero Dependencies: Works with or without external environment libraries
  • Bedrock Compatible: Seamless integration with modern WordPress setups

Installation

Install via Composer:

composer require wp-spaghetti/wp-env

Quick Start

1. Basic Usage

<?phpuseWpSpaghetti\WpEnv\Environment;
// Get environment variables with fallbacks$dbHost = Environment::get('DB_HOST', 'localhost');
$debug = Environment::getBool('WP_DEBUG', false);
$maxUploads = Environment::getInt('MAX_UPLOADS', 10);
$allowedTypes = Environment::getArray('ALLOWED_TYPES', ['jpg', 'png']);
// Check environment typeif (Environment::isDevelopment()) {
// Development-specific codeerror_reporting(E_ALL);
}
// Check containerizationif (Environment::isDocker()) {
// Docker-specific configuration$redisHost = 'redis'; // Use container name
}

2. Configuration Priority

WP Env uses the following priority order:

  1. WordPress Constants (define() in wp-config.php)
  2. .env files (via oscarotero/env if available)
  3. System environment (getenv())
  4. Default values
<?php// wp-config.phpdefine('API_TIMEOUT', 30);
// .env fileAPI_TIMEOUT=60// System environment
export API_TIMEOUT=90// Result: 30 (WordPress constant wins)$timeout = Environment::getInt('API_TIMEOUT', 10);

3. WordPress Integration

<?php// In your plugin or themeuseWpSpaghetti\WpEnv\Environment;
class MyPlugin {
publicfunction__construct() {
// Validate required configuration
Environment::validateRequired([
'MY_PLUGIN_API_KEY',
'MY_PLUGIN_SECRET'
]);
add_action('init', [$this, 'init']);
}
publicfunctioninit(): void {
$config = Environment::load([
'MY_PLUGIN_API_KEY',
'MY_PLUGIN_TIMEOUT' => 30,
'MY_PLUGIN_RETRIES' => 3,
'MY_PLUGIN_ENABLED' => true
]);
// Environment-specific behaviorif (Environment::isProduction()) {
$this->enableCaching();
}
if (Environment::isDebug()) {
$this->enableDetailedLogging();
}
}
}

API Reference

Core Methods

Environment::get(string $key, mixed $default = null): mixed

Get environment variable with fallback to default value.

Environment::getBool(string $key, bool $default = false): bool

Get environment variable as boolean. Recognizes: 1, true, on, yes, enabled.

Environment::getInt(string $key, int $default = 0): int

Get environment variable as integer with type conversion.

Environment::getFloat(string $key, float $default = 0.0): float

Get environment variable as float with type conversion.

Environment::getArray(string $key, array $default = []): array

Get environment variable as array (comma-separated values).

Environment::getRequired(string $key): mixed

Get required environment variable (throws exception if missing).

Validation Methods

Environment::validateRequired(array $keys): void

Validate that all required environment variables are set.

Environment::validateRequired([
'DB_HOST',
'DB_NAME', 'API_KEY'
]);

Environment::load(array $keys): array

Load multiple environment variables at once.

// Simple array$vars = Environment::load(['KEY1', 'KEY2', 'KEY3']);
// With defaults$vars = Environment::load([
'API_URL' => 'https://api.example.com',
'TIMEOUT' => 30,
'ENABLED' => true
]);

Environment Detection

Environment::getEnvironment(): string

Get current environment type: development, staging, or production.

Environment::isDevelopment(): bool

Check if running in development environment.

Environment::isStaging(): bool

Check if running in staging environment.

Environment::isProduction(): bool

Check if running in production environment.

Container Detection

Environment::isDocker(): bool

Check if running inside a Docker container.

Environment::isContainer(): bool

Check if running in any containerized environment (Docker, Podman, etc.).

WordPress-Specific Methods

Environment::isDebug(): bool

Check if WordPress debug mode is enabled (WP_DEBUG).

Environment::isMultisite(): bool

Check if WordPress is running in multisite mode.

Environment::isCli(): bool

Check if running via CLI (WP-CLI or PHP CLI).

Environment::isWeb(): bool

Check if running via web request.

System Information

Environment::getServerSoftware(): string

Get server software (nginx, apache, litespeed, iis).

Environment::getPhpSapi(): string

Get PHP SAPI information.

Utility Methods

Environment::getDebugInfo(): array

Get comprehensive environment information for debugging.

Environment::clearCache(): void

Clear internal caches (useful for testing).

Environment::addSensitiveKey(string $key): void

Add key to sensitive list (prevents caching/logging).

Configuration Examples

WordPress Constants (wp-config.php)

<?php// Basic WordPress configurationdefine('WP_DEBUG', true);
define('WP_ENVIRONMENT_TYPE', 'development');
// Custom application settingsdefine('API_BASE_URL', 'https://api.example.com');
define('CACHE_ENABLED', true);
define('MAX_UPLOAD_SIZE', 50);
define('ALLOWED_EXTENSIONS', 'jpg,png,gif,pdf');
// Container-specific settingsdefine('REDIS_HOST', 'redis');
define('ELASTICSEARCH_URL', 'http://elasticsearch:9200');

Environment File (.env)

# Environment identificationWP_ENVIRONMENT_TYPE=developmentWP_DEBUG=true# Database configurationDB_HOST=dbDB_NAME=wordpressDB_USER=wp_userDB_PASSWORD=secure_password# Application settingsAPI_BASE_URL=https://api.staging.example.comCACHE_TTL=3600MAX_RETRIES=5FEATURE_FLAGS=feature1,feature2,feature3# Container settingsREDIS_HOST=redisREDIS_PORT=6379ELASTICSEARCH_URL=http://elasticsearch:9200

Docker Compose Integration

services:
wordpress:
image: wordpress:latestenvironment:
- WP_ENVIRONMENT_TYPE=development
- WP_DEBUG=true
- DB_HOST=db
- REDIS_HOST=redis
- API_TIMEOUT=60
- DOCKER_CONTAINER=truevolumes:
- .:/var/www/htmldepends_on:
- db
- redisdb:
image: mysql:8.0environment:
- MYSQL_DATABASE=wordpress
- MYSQL_USER=wp_user
- MYSQL_PASSWORD=secure_passwordredis:
image: redis:alpine

Hook System

WP Env provides several WordPress hooks for customization:

Filter Environment Values

// Modify any environment valueadd_filter('wp_env_get_value', function($value, $key, $default) {
// Force debug mode for specific usersif ($key === 'WP_DEBUG' && current_user_can('administrator')) {
returntrue;
}
return$value;
}, 10, 3);

Custom Environment Detection

// Override environment detectionadd_filter('wp_env_get_environment', function($environment, $originalEnv) {
// Custom logic for environment detectionif (str_contains($_SERVER['HTTP_HOST'] ?? '', 'beta.')) {
return'staging';
}
return$environment;
}, 10, 2);

Container Detection Override

// Override Docker detectionadd_filter('wp_env_is_docker', function($isDocker) {
// Custom Docker detection logicreturnfile_exists('/app/.dockerenv');
});

Sensitive Key Protection

// Add custom sensitive keysadd_filter('wp_env_is_sensitive_key', function($isSensitive, $key) {
$customSensitive = [
'STRIPE_SECRET_KEY',
'MAILCHIMP_API_KEY',
'GOOGLE_ANALYTICS_SECRET'
];
return$isSensitive || in_array($key, $customSensitive);
}, 10, 2);

Cache Events

// React to cache clearingadd_action('wp_env_cache_cleared', function() {
// Your custom cache clearing logicwp_cache_flush();
});

Advanced Usage Examples

Plugin Configuration Management

<?phpuseWpSpaghetti\WpEnv\Environment;
class PluginConfigManager {
privatearray$config;
publicfunction__construct() {
$this->loadConfiguration();
}
privatefunctionloadConfiguration(): void {
// Load all plugin settings at once$this->config = Environment::load([
'MYPLUGIN_API_URL' => 'https://api.example.com',
'MYPLUGIN_TIMEOUT' => 30,
'MYPLUGIN_RETRIES' => 3,
'MYPLUGIN_CACHE_TTL' => 3600,
'MYPLUGIN_FEATURES' => [],
'MYPLUGIN_DEBUG' => false
]);
// Environment-specific overridesif (Environment::isDevelopment()) {
$this->config['MYPLUGIN_DEBUG'] = true;
$this->config['MYPLUGIN_TIMEOUT'] = 5; // Shorter timeout for dev
}
if (Environment::isDocker()) {
$this->config['MYPLUGIN_API_URL'] = 'http://api:8080'; // Container URL
}
// Validate critical configurationif (Environment::isProduction()) {
Environment::validateRequired([
'MYPLUGIN_API_KEY',
'MYPLUGIN_SECRET_KEY'
]);
}
}
publicfunctionget(string$key, $default = null) {
return$this->config[$key] ?? $default;
}
}

Environment-Specific Service Registration

<?phpuseWpSpaghetti\WpEnv\Environment;
class ServiceProvider {
publicfunctionregister(): void {
switch (Environment::getEnvironment()) {
case Environment::ENV_DEVELOPMENT:
$this->registerDevelopmentServices();
break;
case Environment::ENV_STAGING:
$this->registerStagingServices();
break;
case Environment::ENV_PRODUCTION:
$this->registerProductionServices();
break;
}
// Container-specific servicesif (Environment::isContainer()) {
$this->registerContainerServices();
}
}
privatefunctionregisterDevelopmentServices(): void {
// Development-only servicesadd_action('wp_footer', [$this, 'addDebugInfo']);
// Use different API endpoints$apiUrl = 'http://localhost:3000/api';
}
privatefunctionregisterProductionServices(): void {
// Production optimizationsadd_action('init', [$this, 'enableCaching']);
// Production API endpoints$apiUrl = Environment::get('PROD_API_URL', 'https://api.example.com');
}
privatefunctionregisterContainerServices(): void {
// Container-specific networking$redisHost = Environment::get('REDIS_HOST', 'redis');
$dbHost = Environment::get('DB_HOST', 'db');
}
}

Multi-Environment Configuration

<?phpuseWpSpaghetti\WpEnv\Environment;
class MultiEnvironmentConfig {
privatearray$environments = [
Environment::ENV_DEVELOPMENT => [
'debug' => true,
'cache_ttl' => 0,
'api_url' => 'http://localhost:3000',
'log_level' => 'debug'
],
Environment::ENV_STAGING => [
'debug' => true,
'cache_ttl' => 300,
'api_url' => 'https://staging-api.example.com',
'log_level' => 'info'
],
Environment::ENV_PRODUCTION => [
'debug' => false,
'cache_ttl' => 3600,
'api_url' => 'https://api.example.com',
'log_level' => 'error'
]
];
publicfunctionget(string$key, $default = null) {
$currentEnv = Environment::getEnvironment();
$envConfig = $this->environments[$currentEnv] ?? [];
// Try environment-specific config firstif (isset($envConfig[$key])) {
return$envConfig[$key];
}
// Fall back to environment variablereturn Environment::get(strtoupper($key), $default);
}
publicfunctiongetApiUrl(): string {
return$this->get('api_url');
}
publicfunctiongetCacheTtl(): int {
return (int) $this->get('cache_ttl');
}
publicfunctionshouldEnableDebug(): bool {
return (bool) $this->get('debug');
}
}

Troubleshooting

Debug Information

// Get comprehensive environment info$info = Environment::getDebugInfo();
print_r($info);
// Check specific valuesecho"Environment: " . Environment::getEnvironment() . "\n";
echo"Is Docker: " . (Environment::isDocker() ? 'yes' : 'no') . "\n";
echo"Debug Mode: " . (Environment::isDebug() ? 'enabled' : 'disabled') . "\n";

Common Issues

Environment not detected correctly:

  • Set WP_ENVIRONMENT_TYPE constant in wp-config.php
  • Use .env file with WP_ENV=development
  • Check domain-based detection logic

Values not loading:

  • Verify constant names (WordPress constants take priority)
  • Check if oscarotero/env is installed for .env support
  • Clear cache with Environment::clearCache()

Container detection issues:

  • Ensure Docker environment variables are set
  • Check if .dockerenv file exists
  • Use custom detection with hooks

Requirements

  • PHP 8.0 or higher
  • WordPress 5.0 or higher (for WordPress-specific features)
  • Optional: oscarotero/env for .env file support

Changelog

Please see CHANGELOG for a detailed list of changes for each release.

We follow Semantic Versioning and use Conventional Commits to automatically generate our changelog.

Release Process

  • Major versions (1.0.0 → 2.0.0): Breaking changes
  • Minor versions (1.0.0 → 1.1.0): New features, backward compatible
  • Patch versions (1.0.0 → 1.0.1): Bug fixes, backward compatible

All releases are automatically created when changes are pushed to the main branch, based on commit message conventions.

Contributing

For your contributions please use:

See CONTRIBUTING for detailed guidelines.

Sponsor

Buy Me A Coffee

License

(ɔ) Copyleft 2026 Frugan.
GNU GPLv3, see LICENSE file.

About

A comprehensive WordPress environment management utility with typed getters, system detection and secure configuration handling

Topics

Resources

Code of conduct

Contributing

Security policy

Stars

0 stars

Watchers

0 watching

Forks

Releases

Sponsor this project

Packages

Contributors

Languages

, 'i'); if (__m === '*' || __re.test(location.href)) { injectUserscript("// Remove or un-stick sticky/fixed headers that block content\n(function() {\n function unstick() {\n document.querySelectorAll('header, nav, [role=\"banner\"], .header, .navbar, .sticky, .fixed-top, [style*=\"position: fixed\"], [style*=\"position:sticky\"]').forEach(function(el) {\n if (el.style.position === 'fixed' || el.style.position === 'sticky' || \n getComputedStyle(el).position === 'fixed' || getComputedStyle(el).position === 'sticky') {\n el.style.position = 'static';\n el.style.top = 'auto';\n el.style.zIndex = 'auto';\n }\n });\n }\n \n unstick();\n \n var observer = new MutationObserver(unstick);\n observer.observe(document.body, { childList: true, subtree: true, attributes: true, attributeFilter: ['style', 'class'] });\n})();", "Kill Sticky Headers"); } } catch(__e) { console.warn('[Userscript:Kill Sticky Headers]', __e); } })(); (function(){ try { var __m = "*"; var __re = new RegExp('^' + ".*" + '
Skip to content

PHP VersionPackagist DownloadsPackagist StarsGitHub Actions Workflow StatusCoverage StatusKnown VulnerabilitiesGitHub Issues

GitHub ReleaseLicense

WP Env

A comprehensive WordPress environment management utility with typed getters, system detection and secure configuration handling.

Features

  • Multi-Source Configuration: WordPress constants, .env files, and getenv() with intelligent priority
  • Typed Getters: Type-safe methods for bool, int, float, and array values
  • Environment Detection: Automatic development, staging, and production environment detection
  • Container Detection: Docker, Kubernetes, Podman, and other containerization detection
  • Performance Caching: Smart caching system with sensitive data protection
  • Security-Focused: Built-in protection for sensitive configuration values
  • WordPress Integration: Native WordPress hooks and filters for customization
  • Zero Dependencies: Works with or without external environment libraries
  • Bedrock Compatible: Seamless integration with modern WordPress setups

Installation

Install via Composer:

composer require wp-spaghetti/wp-env

Quick Start

1. Basic Usage

<?phpuseWpSpaghetti\WpEnv\Environment;
// Get environment variables with fallbacks$dbHost = Environment::get('DB_HOST', 'localhost');
$debug = Environment::getBool('WP_DEBUG', false);
$maxUploads = Environment::getInt('MAX_UPLOADS', 10);
$allowedTypes = Environment::getArray('ALLOWED_TYPES', ['jpg', 'png']);
// Check environment typeif (Environment::isDevelopment()) {
// Development-specific codeerror_reporting(E_ALL);
}
// Check containerizationif (Environment::isDocker()) {
// Docker-specific configuration$redisHost = 'redis'; // Use container name
}

2. Configuration Priority

WP Env uses the following priority order:

  1. WordPress Constants (define() in wp-config.php)
  2. .env files (via oscarotero/env if available)
  3. System environment (getenv())
  4. Default values
<?php// wp-config.phpdefine('API_TIMEOUT', 30);
// .env fileAPI_TIMEOUT=60// System environment
export API_TIMEOUT=90// Result: 30 (WordPress constant wins)$timeout = Environment::getInt('API_TIMEOUT', 10);

3. WordPress Integration

<?php// In your plugin or themeuseWpSpaghetti\WpEnv\Environment;
class MyPlugin {
publicfunction__construct() {
// Validate required configuration
Environment::validateRequired([
'MY_PLUGIN_API_KEY',
'MY_PLUGIN_SECRET'
]);
add_action('init', [$this, 'init']);
}
publicfunctioninit(): void {
$config = Environment::load([
'MY_PLUGIN_API_KEY',
'MY_PLUGIN_TIMEOUT' => 30,
'MY_PLUGIN_RETRIES' => 3,
'MY_PLUGIN_ENABLED' => true
]);
// Environment-specific behaviorif (Environment::isProduction()) {
$this->enableCaching();
}
if (Environment::isDebug()) {
$this->enableDetailedLogging();
}
}
}

API Reference

Core Methods

Environment::get(string $key, mixed $default = null): mixed

Get environment variable with fallback to default value.

Environment::getBool(string $key, bool $default = false): bool

Get environment variable as boolean. Recognizes: 1, true, on, yes, enabled.

Environment::getInt(string $key, int $default = 0): int

Get environment variable as integer with type conversion.

Environment::getFloat(string $key, float $default = 0.0): float

Get environment variable as float with type conversion.

Environment::getArray(string $key, array $default = []): array

Get environment variable as array (comma-separated values).

Environment::getRequired(string $key): mixed

Get required environment variable (throws exception if missing).

Validation Methods

Environment::validateRequired(array $keys): void

Validate that all required environment variables are set.

Environment::validateRequired([
'DB_HOST',
'DB_NAME', 'API_KEY'
]);

Environment::load(array $keys): array

Load multiple environment variables at once.

// Simple array$vars = Environment::load(['KEY1', 'KEY2', 'KEY3']);
// With defaults$vars = Environment::load([
'API_URL' => 'https://api.example.com',
'TIMEOUT' => 30,
'ENABLED' => true
]);

Environment Detection

Environment::getEnvironment(): string

Get current environment type: development, staging, or production.

Environment::isDevelopment(): bool

Check if running in development environment.

Environment::isStaging(): bool

Check if running in staging environment.

Environment::isProduction(): bool

Check if running in production environment.

Container Detection

Environment::isDocker(): bool

Check if running inside a Docker container.

Environment::isContainer(): bool

Check if running in any containerized environment (Docker, Podman, etc.).

WordPress-Specific Methods

Environment::isDebug(): bool

Check if WordPress debug mode is enabled (WP_DEBUG).

Environment::isMultisite(): bool

Check if WordPress is running in multisite mode.

Environment::isCli(): bool

Check if running via CLI (WP-CLI or PHP CLI).

Environment::isWeb(): bool

Check if running via web request.

System Information

Environment::getServerSoftware(): string

Get server software (nginx, apache, litespeed, iis).

Environment::getPhpSapi(): string

Get PHP SAPI information.

Utility Methods

Environment::getDebugInfo(): array

Get comprehensive environment information for debugging.

Environment::clearCache(): void

Clear internal caches (useful for testing).

Environment::addSensitiveKey(string $key): void

Add key to sensitive list (prevents caching/logging).

Configuration Examples

WordPress Constants (wp-config.php)

<?php// Basic WordPress configurationdefine('WP_DEBUG', true);
define('WP_ENVIRONMENT_TYPE', 'development');
// Custom application settingsdefine('API_BASE_URL', 'https://api.example.com');
define('CACHE_ENABLED', true);
define('MAX_UPLOAD_SIZE', 50);
define('ALLOWED_EXTENSIONS', 'jpg,png,gif,pdf');
// Container-specific settingsdefine('REDIS_HOST', 'redis');
define('ELASTICSEARCH_URL', 'http://elasticsearch:9200');

Environment File (.env)

# Environment identificationWP_ENVIRONMENT_TYPE=developmentWP_DEBUG=true# Database configurationDB_HOST=dbDB_NAME=wordpressDB_USER=wp_userDB_PASSWORD=secure_password# Application settingsAPI_BASE_URL=https://api.staging.example.comCACHE_TTL=3600MAX_RETRIES=5FEATURE_FLAGS=feature1,feature2,feature3# Container settingsREDIS_HOST=redisREDIS_PORT=6379ELASTICSEARCH_URL=http://elasticsearch:9200

Docker Compose Integration

services:
wordpress:
image: wordpress:latestenvironment:
- WP_ENVIRONMENT_TYPE=development
- WP_DEBUG=true
- DB_HOST=db
- REDIS_HOST=redis
- API_TIMEOUT=60
- DOCKER_CONTAINER=truevolumes:
- .:/var/www/htmldepends_on:
- db
- redisdb:
image: mysql:8.0environment:
- MYSQL_DATABASE=wordpress
- MYSQL_USER=wp_user
- MYSQL_PASSWORD=secure_passwordredis:
image: redis:alpine

Hook System

WP Env provides several WordPress hooks for customization:

Filter Environment Values

// Modify any environment valueadd_filter('wp_env_get_value', function($value, $key, $default) {
// Force debug mode for specific usersif ($key === 'WP_DEBUG' && current_user_can('administrator')) {
returntrue;
}
return$value;
}, 10, 3);

Custom Environment Detection

// Override environment detectionadd_filter('wp_env_get_environment', function($environment, $originalEnv) {
// Custom logic for environment detectionif (str_contains($_SERVER['HTTP_HOST'] ?? '', 'beta.')) {
return'staging';
}
return$environment;
}, 10, 2);

Container Detection Override

// Override Docker detectionadd_filter('wp_env_is_docker', function($isDocker) {
// Custom Docker detection logicreturnfile_exists('/app/.dockerenv');
});

Sensitive Key Protection

// Add custom sensitive keysadd_filter('wp_env_is_sensitive_key', function($isSensitive, $key) {
$customSensitive = [
'STRIPE_SECRET_KEY',
'MAILCHIMP_API_KEY',
'GOOGLE_ANALYTICS_SECRET'
];
return$isSensitive || in_array($key, $customSensitive);
}, 10, 2);

Cache Events

// React to cache clearingadd_action('wp_env_cache_cleared', function() {
// Your custom cache clearing logicwp_cache_flush();
});

Advanced Usage Examples

Plugin Configuration Management

<?phpuseWpSpaghetti\WpEnv\Environment;
class PluginConfigManager {
privatearray$config;
publicfunction__construct() {
$this->loadConfiguration();
}
privatefunctionloadConfiguration(): void {
// Load all plugin settings at once$this->config = Environment::load([
'MYPLUGIN_API_URL' => 'https://api.example.com',
'MYPLUGIN_TIMEOUT' => 30,
'MYPLUGIN_RETRIES' => 3,
'MYPLUGIN_CACHE_TTL' => 3600,
'MYPLUGIN_FEATURES' => [],
'MYPLUGIN_DEBUG' => false
]);
// Environment-specific overridesif (Environment::isDevelopment()) {
$this->config['MYPLUGIN_DEBUG'] = true;
$this->config['MYPLUGIN_TIMEOUT'] = 5; // Shorter timeout for dev
}
if (Environment::isDocker()) {
$this->config['MYPLUGIN_API_URL'] = 'http://api:8080'; // Container URL
}
// Validate critical configurationif (Environment::isProduction()) {
Environment::validateRequired([
'MYPLUGIN_API_KEY',
'MYPLUGIN_SECRET_KEY'
]);
}
}
publicfunctionget(string$key, $default = null) {
return$this->config[$key] ?? $default;
}
}

Environment-Specific Service Registration

<?phpuseWpSpaghetti\WpEnv\Environment;
class ServiceProvider {
publicfunctionregister(): void {
switch (Environment::getEnvironment()) {
case Environment::ENV_DEVELOPMENT:
$this->registerDevelopmentServices();
break;
case Environment::ENV_STAGING:
$this->registerStagingServices();
break;
case Environment::ENV_PRODUCTION:
$this->registerProductionServices();
break;
}
// Container-specific servicesif (Environment::isContainer()) {
$this->registerContainerServices();
}
}
privatefunctionregisterDevelopmentServices(): void {
// Development-only servicesadd_action('wp_footer', [$this, 'addDebugInfo']);
// Use different API endpoints$apiUrl = 'http://localhost:3000/api';
}
privatefunctionregisterProductionServices(): void {
// Production optimizationsadd_action('init', [$this, 'enableCaching']);
// Production API endpoints$apiUrl = Environment::get('PROD_API_URL', 'https://api.example.com');
}
privatefunctionregisterContainerServices(): void {
// Container-specific networking$redisHost = Environment::get('REDIS_HOST', 'redis');
$dbHost = Environment::get('DB_HOST', 'db');
}
}

Multi-Environment Configuration

<?phpuseWpSpaghetti\WpEnv\Environment;
class MultiEnvironmentConfig {
privatearray$environments = [
Environment::ENV_DEVELOPMENT => [
'debug' => true,
'cache_ttl' => 0,
'api_url' => 'http://localhost:3000',
'log_level' => 'debug'
],
Environment::ENV_STAGING => [
'debug' => true,
'cache_ttl' => 300,
'api_url' => 'https://staging-api.example.com',
'log_level' => 'info'
],
Environment::ENV_PRODUCTION => [
'debug' => false,
'cache_ttl' => 3600,
'api_url' => 'https://api.example.com',
'log_level' => 'error'
]
];
publicfunctionget(string$key, $default = null) {
$currentEnv = Environment::getEnvironment();
$envConfig = $this->environments[$currentEnv] ?? [];
// Try environment-specific config firstif (isset($envConfig[$key])) {
return$envConfig[$key];
}
// Fall back to environment variablereturn Environment::get(strtoupper($key), $default);
}
publicfunctiongetApiUrl(): string {
return$this->get('api_url');
}
publicfunctiongetCacheTtl(): int {
return (int) $this->get('cache_ttl');
}
publicfunctionshouldEnableDebug(): bool {
return (bool) $this->get('debug');
}
}

Troubleshooting

Debug Information

// Get comprehensive environment info$info = Environment::getDebugInfo();
print_r($info);
// Check specific valuesecho"Environment: " . Environment::getEnvironment() . "\n";
echo"Is Docker: " . (Environment::isDocker() ? 'yes' : 'no') . "\n";
echo"Debug Mode: " . (Environment::isDebug() ? 'enabled' : 'disabled') . "\n";

Common Issues

Environment not detected correctly:

  • Set WP_ENVIRONMENT_TYPE constant in wp-config.php
  • Use .env file with WP_ENV=development
  • Check domain-based detection logic

Values not loading:

  • Verify constant names (WordPress constants take priority)
  • Check if oscarotero/env is installed for .env support
  • Clear cache with Environment::clearCache()

Container detection issues:

  • Ensure Docker environment variables are set
  • Check if .dockerenv file exists
  • Use custom detection with hooks

Requirements

  • PHP 8.0 or higher
  • WordPress 5.0 or higher (for WordPress-specific features)
  • Optional: oscarotero/env for .env file support

Changelog

Please see CHANGELOG for a detailed list of changes for each release.

We follow Semantic Versioning and use Conventional Commits to automatically generate our changelog.

Release Process

  • Major versions (1.0.0 → 2.0.0): Breaking changes
  • Minor versions (1.0.0 → 1.1.0): New features, backward compatible
  • Patch versions (1.0.0 → 1.0.1): Bug fixes, backward compatible

All releases are automatically created when changes are pushed to the main branch, based on commit message conventions.

Contributing

For your contributions please use:

See CONTRIBUTING for detailed guidelines.

Sponsor

Buy Me A Coffee

License

(ɔ) Copyleft 2026 Frugan.
GNU GPLv3, see LICENSE file.

About

A comprehensive WordPress environment management utility with typed getters, system detection and secure configuration handling

Topics

Resources

Code of conduct

Contributing

Security policy

Stars

0 stars

Watchers

0 watching

Forks

Releases

Sponsor this project

Packages

Contributors

Languages

, 'i'); if (__m === '*' || __re.test(location.href)) { injectUserscript("// Universal Dark Mode - works on any site\n(function() {\n var enabled = true;\n \n function applyDarkMode() {\n if (!enabled) return;\n \n // Create style element if it doesn't exist\n var style = document.getElementById('universal-dark-mode-style');\n if (!style) {\n style = document.createElement('style');\n style.id = 'universal-dark-mode-style';\n document.head.appendChild(style);\n }\n \n // Dark mode CSS - inverts colors but preserves images/video\n style.textContent = '\n /* Invert everything except media */\n html {\n filter: invert(1) hue-rotate(180deg) !important;\n background: #1a1a2e !important;\n }\n \n /* Restore images, videos, iframes, canvas */\n img, video, iframe, canvas, svg, picture, [style*=\"background-image\"] {\n filter: invert(1) hue-rotate(180deg) !important;\n }\n \n /* Preserve specific elements that should not be inverted */\n .no-dark-mode, .no-dark-mode *,\n [data-theme=\"light\"], [data-theme=\"light\"],\n .ace_editor, .ace_editor *,\n .CodeMirror, .CodeMirror *,\n .monaco-editor, .monaco-editor *,\n .markdown-body pre, .markdown-body pre *,\n .highlight, .highlight *,\n pre code, pre code * {\n filter: none !important;\n }\n \n /* Fix common UI elements */\n .modal, .popup, .dropdown-menu, .tooltip, .popover {\n filter: invert(1) hue-rotate(180deg) !important;\n background: #2d2d44 !important;\n border-color: #444 !important;\n }\n \n /* Scrollbars */\n ::-webkit-scrollbar { background: #1a1a2e !important; }\n ::-webkit-scrollbar-thumb { background: #444 !important; }\n ::-webkit-scrollbar-thumb:hover { background: #555 !important; }\n \n /* Selection */\n ::selection { background: #4ecdc4 !important; color: #1a1a2e !important; }\n ::-moz-selection { background: #4ecdc4 !important; color: #1a1a2e !important; }\n ';\n }\n \n function removeDarkMode() {\n var style = document.getElementById('universal-dark-mode-style');\n if (style) style.remove();\n }\n \n // Toggle with Alt+Shift+D\n document.addEventListener('keydown', function(e) {\n if (e.altKey && e.shiftKey && e.key === 'D') {\n e.preventDefault();\n enabled = !enabled;\n if (enabled) {\n applyDarkMode();\n console.log('[Universal Dark Mode] Enabled');\n } else {\n removeDarkMode();\n console.log('[Universal Dark Mode] Disabled');\n }\n }\n });\n \n // Apply on load\n applyDarkMode();\n \n // Re-apply on dynamic content\n var observer = new MutationObserver(function(mutations) {\n if (enabled && !document.getElementById('universal-dark-mode-style')) {\n applyDarkMode();\n }\n });\n observer.observe(document.head, { childList: true });\n \n console.log('[Universal Dark Mode] Loaded - Press Alt+Shift+D to toggle');\n})();", "Universal Dark Mode"); } } catch(__e) { console.warn('[Userscript:Universal Dark Mode]', __e); } })(); })();
Skip to content

PHP VersionPackagist DownloadsPackagist StarsGitHub Actions Workflow StatusCoverage StatusKnown VulnerabilitiesGitHub Issues

GitHub ReleaseLicense

WP Env

A comprehensive WordPress environment management utility with typed getters, system detection and secure configuration handling.

Features

  • Multi-Source Configuration: WordPress constants, .env files, and getenv() with intelligent priority
  • Typed Getters: Type-safe methods for bool, int, float, and array values
  • Environment Detection: Automatic development, staging, and production environment detection
  • Container Detection: Docker, Kubernetes, Podman, and other containerization detection
  • Performance Caching: Smart caching system with sensitive data protection
  • Security-Focused: Built-in protection for sensitive configuration values
  • WordPress Integration: Native WordPress hooks and filters for customization
  • Zero Dependencies: Works with or without external environment libraries
  • Bedrock Compatible: Seamless integration with modern WordPress setups

Installation

Install via Composer:

composer require wp-spaghetti/wp-env

Quick Start

1. Basic Usage

<?phpuseWpSpaghetti\WpEnv\Environment;
// Get environment variables with fallbacks$dbHost = Environment::get('DB_HOST', 'localhost');
$debug = Environment::getBool('WP_DEBUG', false);
$maxUploads = Environment::getInt('MAX_UPLOADS', 10);
$allowedTypes = Environment::getArray('ALLOWED_TYPES', ['jpg', 'png']);
// Check environment typeif (Environment::isDevelopment()) {
// Development-specific codeerror_reporting(E_ALL);
}
// Check containerizationif (Environment::isDocker()) {
// Docker-specific configuration$redisHost = 'redis'; // Use container name
}

2. Configuration Priority

WP Env uses the following priority order:

  1. WordPress Constants (define() in wp-config.php)
  2. .env files (via oscarotero/env if available)
  3. System environment (getenv())
  4. Default values
<?php// wp-config.phpdefine('API_TIMEOUT', 30);
// .env fileAPI_TIMEOUT=60// System environment
export API_TIMEOUT=90// Result: 30 (WordPress constant wins)$timeout = Environment::getInt('API_TIMEOUT', 10);

3. WordPress Integration

<?php// In your plugin or themeuseWpSpaghetti\WpEnv\Environment;
class MyPlugin {
publicfunction__construct() {
// Validate required configuration
Environment::validateRequired([
'MY_PLUGIN_API_KEY',
'MY_PLUGIN_SECRET'
]);
add_action('init', [$this, 'init']);
}
publicfunctioninit(): void {
$config = Environment::load([
'MY_PLUGIN_API_KEY',
'MY_PLUGIN_TIMEOUT' => 30,
'MY_PLUGIN_RETRIES' => 3,
'MY_PLUGIN_ENABLED' => true
]);
// Environment-specific behaviorif (Environment::isProduction()) {
$this->enableCaching();
}
if (Environment::isDebug()) {
$this->enableDetailedLogging();
}
}
}

API Reference

Core Methods

Environment::get(string $key, mixed $default = null): mixed

Get environment variable with fallback to default value.

Environment::getBool(string $key, bool $default = false): bool

Get environment variable as boolean. Recognizes: 1, true, on, yes, enabled.

Environment::getInt(string $key, int $default = 0): int

Get environment variable as integer with type conversion.

Environment::getFloat(string $key, float $default = 0.0): float

Get environment variable as float with type conversion.

Environment::getArray(string $key, array $default = []): array

Get environment variable as array (comma-separated values).

Environment::getRequired(string $key): mixed

Get required environment variable (throws exception if missing).

Validation Methods

Environment::validateRequired(array $keys): void

Validate that all required environment variables are set.

Environment::validateRequired([
'DB_HOST',
'DB_NAME', 'API_KEY'
]);

Environment::load(array $keys): array

Load multiple environment variables at once.

// Simple array$vars = Environment::load(['KEY1', 'KEY2', 'KEY3']);
// With defaults$vars = Environment::load([
'API_URL' => 'https://api.example.com',
'TIMEOUT' => 30,
'ENABLED' => true
]);

Environment Detection

Environment::getEnvironment(): string

Get current environment type: development, staging, or production.

Environment::isDevelopment(): bool

Check if running in development environment.

Environment::isStaging(): bool

Check if running in staging environment.

Environment::isProduction(): bool

Check if running in production environment.

Container Detection

Environment::isDocker(): bool

Check if running inside a Docker container.

Environment::isContainer(): bool

Check if running in any containerized environment (Docker, Podman, etc.).

WordPress-Specific Methods

Environment::isDebug(): bool

Check if WordPress debug mode is enabled (WP_DEBUG).

Environment::isMultisite(): bool

Check if WordPress is running in multisite mode.

Environment::isCli(): bool

Check if running via CLI (WP-CLI or PHP CLI).

Environment::isWeb(): bool

Check if running via web request.

System Information

Environment::getServerSoftware(): string

Get server software (nginx, apache, litespeed, iis).

Environment::getPhpSapi(): string

Get PHP SAPI information.

Utility Methods

Environment::getDebugInfo(): array

Get comprehensive environment information for debugging.

Environment::clearCache(): void

Clear internal caches (useful for testing).

Environment::addSensitiveKey(string $key): void

Add key to sensitive list (prevents caching/logging).

Configuration Examples

WordPress Constants (wp-config.php)

<?php// Basic WordPress configurationdefine('WP_DEBUG', true);
define('WP_ENVIRONMENT_TYPE', 'development');
// Custom application settingsdefine('API_BASE_URL', 'https://api.example.com');
define('CACHE_ENABLED', true);
define('MAX_UPLOAD_SIZE', 50);
define('ALLOWED_EXTENSIONS', 'jpg,png,gif,pdf');
// Container-specific settingsdefine('REDIS_HOST', 'redis');
define('ELASTICSEARCH_URL', 'http://elasticsearch:9200');

Environment File (.env)

# Environment identificationWP_ENVIRONMENT_TYPE=developmentWP_DEBUG=true# Database configurationDB_HOST=dbDB_NAME=wordpressDB_USER=wp_userDB_PASSWORD=secure_password# Application settingsAPI_BASE_URL=https://api.staging.example.comCACHE_TTL=3600MAX_RETRIES=5FEATURE_FLAGS=feature1,feature2,feature3# Container settingsREDIS_HOST=redisREDIS_PORT=6379ELASTICSEARCH_URL=http://elasticsearch:9200

Docker Compose Integration

services:
wordpress:
image: wordpress:latestenvironment:
- WP_ENVIRONMENT_TYPE=development
- WP_DEBUG=true
- DB_HOST=db
- REDIS_HOST=redis
- API_TIMEOUT=60
- DOCKER_CONTAINER=truevolumes:
- .:/var/www/htmldepends_on:
- db
- redisdb:
image: mysql:8.0environment:
- MYSQL_DATABASE=wordpress
- MYSQL_USER=wp_user
- MYSQL_PASSWORD=secure_passwordredis:
image: redis:alpine

Hook System

WP Env provides several WordPress hooks for customization:

Filter Environment Values

// Modify any environment valueadd_filter('wp_env_get_value', function($value, $key, $default) {
// Force debug mode for specific usersif ($key === 'WP_DEBUG' && current_user_can('administrator')) {
returntrue;
}
return$value;
}, 10, 3);

Custom Environment Detection

// Override environment detectionadd_filter('wp_env_get_environment', function($environment, $originalEnv) {
// Custom logic for environment detectionif (str_contains($_SERVER['HTTP_HOST'] ?? '', 'beta.')) {
return'staging';
}
return$environment;
}, 10, 2);

Container Detection Override

// Override Docker detectionadd_filter('wp_env_is_docker', function($isDocker) {
// Custom Docker detection logicreturnfile_exists('/app/.dockerenv');
});

Sensitive Key Protection

// Add custom sensitive keysadd_filter('wp_env_is_sensitive_key', function($isSensitive, $key) {
$customSensitive = [
'STRIPE_SECRET_KEY',
'MAILCHIMP_API_KEY',
'GOOGLE_ANALYTICS_SECRET'
];
return$isSensitive || in_array($key, $customSensitive);
}, 10, 2);

Cache Events

// React to cache clearingadd_action('wp_env_cache_cleared', function() {
// Your custom cache clearing logicwp_cache_flush();
});

Advanced Usage Examples

Plugin Configuration Management

<?phpuseWpSpaghetti\WpEnv\Environment;
class PluginConfigManager {
privatearray$config;
publicfunction__construct() {
$this->loadConfiguration();
}
privatefunctionloadConfiguration(): void {
// Load all plugin settings at once$this->config = Environment::load([
'MYPLUGIN_API_URL' => 'https://api.example.com',
'MYPLUGIN_TIMEOUT' => 30,
'MYPLUGIN_RETRIES' => 3,
'MYPLUGIN_CACHE_TTL' => 3600,
'MYPLUGIN_FEATURES' => [],
'MYPLUGIN_DEBUG' => false
]);
// Environment-specific overridesif (Environment::isDevelopment()) {
$this->config['MYPLUGIN_DEBUG'] = true;
$this->config['MYPLUGIN_TIMEOUT'] = 5; // Shorter timeout for dev
}
if (Environment::isDocker()) {
$this->config['MYPLUGIN_API_URL'] = 'http://api:8080'; // Container URL
}
// Validate critical configurationif (Environment::isProduction()) {
Environment::validateRequired([
'MYPLUGIN_API_KEY',
'MYPLUGIN_SECRET_KEY'
]);
}
}
publicfunctionget(string$key, $default = null) {
return$this->config[$key] ?? $default;
}
}

Environment-Specific Service Registration

<?phpuseWpSpaghetti\WpEnv\Environment;
class ServiceProvider {
publicfunctionregister(): void {
switch (Environment::getEnvironment()) {
case Environment::ENV_DEVELOPMENT:
$this->registerDevelopmentServices();
break;
case Environment::ENV_STAGING:
$this->registerStagingServices();
break;
case Environment::ENV_PRODUCTION:
$this->registerProductionServices();
break;
}
// Container-specific servicesif (Environment::isContainer()) {
$this->registerContainerServices();
}
}
privatefunctionregisterDevelopmentServices(): void {
// Development-only servicesadd_action('wp_footer', [$this, 'addDebugInfo']);
// Use different API endpoints$apiUrl = 'http://localhost:3000/api';
}
privatefunctionregisterProductionServices(): void {
// Production optimizationsadd_action('init', [$this, 'enableCaching']);
// Production API endpoints$apiUrl = Environment::get('PROD_API_URL', 'https://api.example.com');
}
privatefunctionregisterContainerServices(): void {
// Container-specific networking$redisHost = Environment::get('REDIS_HOST', 'redis');
$dbHost = Environment::get('DB_HOST', 'db');
}
}

Multi-Environment Configuration

<?phpuseWpSpaghetti\WpEnv\Environment;
class MultiEnvironmentConfig {
privatearray$environments = [
Environment::ENV_DEVELOPMENT => [
'debug' => true,
'cache_ttl' => 0,
'api_url' => 'http://localhost:3000',
'log_level' => 'debug'
],
Environment::ENV_STAGING => [
'debug' => true,
'cache_ttl' => 300,
'api_url' => 'https://staging-api.example.com',
'log_level' => 'info'
],
Environment::ENV_PRODUCTION => [
'debug' => false,
'cache_ttl' => 3600,
'api_url' => 'https://api.example.com',
'log_level' => 'error'
]
];
publicfunctionget(string$key, $default = null) {
$currentEnv = Environment::getEnvironment();
$envConfig = $this->environments[$currentEnv] ?? [];
// Try environment-specific config firstif (isset($envConfig[$key])) {
return$envConfig[$key];
}
// Fall back to environment variablereturn Environment::get(strtoupper($key), $default);
}
publicfunctiongetApiUrl(): string {
return$this->get('api_url');
}
publicfunctiongetCacheTtl(): int {
return (int) $this->get('cache_ttl');
}
publicfunctionshouldEnableDebug(): bool {
return (bool) $this->get('debug');
}
}

Troubleshooting

Debug Information

// Get comprehensive environment info$info = Environment::getDebugInfo();
print_r($info);
// Check specific valuesecho"Environment: " . Environment::getEnvironment() . "\n";
echo"Is Docker: " . (Environment::isDocker() ? 'yes' : 'no') . "\n";
echo"Debug Mode: " . (Environment::isDebug() ? 'enabled' : 'disabled') . "\n";

Common Issues

Environment not detected correctly:

  • Set WP_ENVIRONMENT_TYPE constant in wp-config.php
  • Use .env file with WP_ENV=development
  • Check domain-based detection logic

Values not loading:

  • Verify constant names (WordPress constants take priority)
  • Check if oscarotero/env is installed for .env support
  • Clear cache with Environment::clearCache()

Container detection issues:

  • Ensure Docker environment variables are set
  • Check if .dockerenv file exists
  • Use custom detection with hooks

Requirements

  • PHP 8.0 or higher
  • WordPress 5.0 or higher (for WordPress-specific features)
  • Optional: oscarotero/env for .env file support

Changelog

Please see CHANGELOG for a detailed list of changes for each release.

We follow Semantic Versioning and use Conventional Commits to automatically generate our changelog.

Release Process

  • Major versions (1.0.0 → 2.0.0): Breaking changes
  • Minor versions (1.0.0 → 1.1.0): New features, backward compatible
  • Patch versions (1.0.0 → 1.0.1): Bug fixes, backward compatible

All releases are automatically created when changes are pushed to the main branch, based on commit message conventions.

Contributing

For your contributions please use:

See CONTRIBUTING for detailed guidelines.

Sponsor

Buy Me A Coffee

License

(ɔ) Copyleft 2026 Frugan.
GNU GPLv3, see LICENSE file.

About

A comprehensive WordPress environment management utility with typed getters, system detection and secure configuration handling

Topics

Resources

Code of conduct

Contributing

Security policy

Stars

0 stars

Watchers

0 watching

Forks

Releases

Sponsor this project

Packages

Contributors

Languages