Different WordPress Settings based on if WP-CLI is running

Today, I was running WP-CLI scripts on my local install, which requires the DB_HOST value to be set to localhost, whereas WP-CLI only works when the host is set to  When I investigated this issue a bit further, I realized that it’s possible to determine the context from which PHP is called using the native PHP function:


SAPI is short for server API and this function will return the server interface that PHP is using when it’s invoked. For example, if you’re running a WP-CLI command, PHP is invoked using the CLI, so php_sapi_name would return ‘cli’.  Thus, you can figure out whether PHP is running from the CLI or not and set the values accordingly.  In my case, I needed to add a conditional to the DB_HOST value and ended up with the following code in wp-config.php:

if ( php_sapi_name() == 'cli' ) {
 define( 'DB_HOST', '' );
else {
 define( 'DB_HOST', 'localhost:33060' );