如何使用条件语句使 wp-cli 在 wp-config 文件中工作?

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

我正在测试使用 wp-cli 为我的域更新我的 proddevstagingtestupdate 站点.

在我的wp-config文件中有条件语句然后我得到以下错误:

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.

这就是我对 wp-config.php 文件进行编码的方式!!!

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

有什么办法可以让 wp-cli 使用这个文件吗?

$_SERVER["HTTP_HOST"]
当您从命令行使用 PHP 时,

不存在。您最好的选择是在命令行中使用该文件时指定一个案例,例如:

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

因为我不太确定你在 wp-cli 中想要 $db_name 是什么,所以我没有在第一组大括号中设置它。