Search code examples
phpwordpresswp-cli

How to make the wp-cli work in wp-config file with conditional statements?


I am testing using the wp-cli to update my prod,dev,staging,test,and update sites for my domain.

In mywp-config file has conditional statements then I get the following error:

PHP Notice:  Undefined index: HTTP_HOST in phar:///usr/local/bin/wp/php/WP_CLI/Runner.php(1070) : eval()'d code on line 22
PHP Notice:  Undefined index: HTTP_HOST in phar:///usr/local/bin/wp/php/WP_CLI/Runner.php(1070) : eval()'d code on line 24
PHP Notice:  Undefined index: HTTP_HOST in phar:///usr/local/bin/wp/php/WP_CLI/Runner.php(1070) : eval()'d code on line 26
PHP Notice:  Undefined index: HTTP_HOST in phar:///usr/local/bin/wp/php/WP_CLI/Runner.php(1070) : eval()'d code on line 28
PHP Notice:  Undefined variable: db_name in phar:///usr/local/bin/wp/php/WP_CLI/Runner.php(1070) : eval()'d code on line 34
Error: Can’t select database. We were able to connect to the database server (which means your username and password is okay) but not able to select the `` database.

This is how I code my wp-config.php file which works!!!

if ($_SERVER["HTTP_HOST"] === 'example.com') {
  $db_name = 'example';
}else if ($_SERVER["HTTP_HOST"] === 'dev.example.com') {
  $db_name = 'example_dev';
}else if ($_SERVER["HTTP_HOST"] === 'staging.example.com'){
  $db_name = 'example_staging';
}else if ($_SERVER["HTTP_HOST"] === 'update.example.com') {
  $db_name = 'example_update';
}

define('DB_NAME', $db_name);

Is there any way I can get the wp-cli to work with this file?


Solution

  • $_SERVER["HTTP_HOST"]
    

    Doesn't exist when you are using PHP from a command line. Your best option would be to specify a case when you are using the file in a command line, for example:

    if (php_sapi_name() == "cli") {
        //set db_name when in cli
    } else {
        //set db_name as per host
        if ($_SERVER["HTTP_HOST"] === 'example.com') {
          $db_name = 'example';
        }else if ($_SERVER["HTTP_HOST"] === 'dev.example.com') {
          $db_name = 'example_dev';
        }else if ($_SERVER["HTTP_HOST"] === 'staging.example.com'){
          $db_name = 'example_staging';
        }else if ($_SERVER["HTTP_HOST"] === 'update.example.com') {
          $db_name = 'example_update';
        }
    }
    

    As im not too sure what you want $db_name to be when you are in wp-cli i have left out setting it in the first set of braces.