From 335fdaa026985e1fb7daffc68dfb17d9616a377b Mon Sep 17 00:00:00 2001 From: Sean Fisher Date: Wed, 19 Jul 2023 16:12:47 -0400 Subject: [PATCH] Allow the environment to be filtered --- README.md | 16 +++++++++++++++- wp-environment-switcher.php | 25 ++++++++++++++++++++++++- 2 files changed, 39 insertions(+), 2 deletions(-) diff --git a/README.md b/README.md index eba1553..c6e02e2 100644 --- a/README.md +++ b/README.md @@ -20,7 +20,21 @@ Activate the plugin in WordPress and you will see the switcher appear in the top ![Screenshot of plugin](https://github.com/alleyinteractive/wp-environment-switcher/assets/346399/83684c99-4f74-4969-b302-a0c617c17190) -The plugin reads the current WordPress environment from `wp_get_environment_type()` which can be set by defining `WP_ENVIRONMENT_TYPE` in your `wp-config.php` file. You can define the available environments by using the `wp_environment_switcher_environments` filter: +The plugin reads the current WordPress environment from the current hosting +provider (Pantheon and WordPress VIP supported) and falls back to +`wp_get_environment_type()` which can be set by defining `WP_ENVIRONMENT_TYPE` +in your `wp-config.php` file. You can override the current environment by +using the `wp_environment_switcher_current_environment` filter: + +```php +add_filter( + 'wp_environment_switcher_current_environment', + fn () => 'my-custom-environment' +); +``` + +You can define the available environments by using the +`wp_environment_switcher_environments` filter: ```php add_filter( diff --git a/wp-environment-switcher.php b/wp-environment-switcher.php index a6dfd6e..044e5b9 100644 --- a/wp-environment-switcher.php +++ b/wp-environment-switcher.php @@ -38,6 +38,29 @@ function get_environments(): array { return (array) apply_filters( 'wp_environment_switcher_environments', [] ); } +/** + * Retrieve the current environment name. + * + * Will attempt to infer the environment from the hosting provider and fallback + * to the WP_ENVIRONMENT_TYPE constant. + * + * @return string + */ +function get_current_environment(): string { + $default = match ( true ) { + ! empty( $_ENV['PANTHEON_ENVIRONMENT'] ) => (string) $_ENV['PANTHEON_ENVIRONMENT'], + defined( 'VIP_GO_APP_ENVIRONMENT' ) => (string) VIP_GO_APP_ENVIRONMENT, + default => (string) wp_get_environment_type(), + }; + + /** + * Filter the current environment name. + * + * @param string $default The current environment. + */ + return (string) apply_filters( 'wp_environment_switcher_current_environment', $default ); +} + /** * Translate the current request path to a different host. * @@ -65,7 +88,7 @@ function register_admin_bar(): void { return; } - $current = wp_get_environment_type(); + $current = get_current_environment(); // Bail if we can't determine the current environment. if ( empty( $current ) ) {