21

I use the wonderful WP-CLI tool. Due to dependence on Apache environment variables for a specific use case, I need to enable a bit of code to run only when running under WP-CLI. How can I detect if WP is running under WP-CLI?

In this specific case I could check for the presence of the Apache environment variables in question. However, I would like to know the more general, canonical method to check. Thank you.

24

Within the php/wp-cli.php we find these lines:

// Can be used by plugins/themes to check if WP-CLI is running or not
define( 'WP_CLI', true );
define( 'WP_CLI_VERSION', trim( file_get_contents( WP_CLI_ROOT . '/VERSION' ) ) );
define( 'WP_CLI_START_MICROTIME', microtime( true ) );

so you could check if WP_CLI or WP_CLI_VERSION are defined.

  • 7
    WP_CLI is the preferred constant to check – Daniel Bachhuber May 10 '16 at 11:55
  • Thanks for commenting - yes and also much shorter, was just wondering about other possibilities ;-) @DanielBachhuber – birgire May 10 '16 at 12:27
  • @dotancohen you should consider accepting the answer by Ryan McCue instead, as it shows explicitly how to check it. – birgire May 10 '16 at 14:20
  • @birgire, may I ask you to have a look at a custom field related question here : wordpress.stackexchange.com/questions/265852/… ? – Istiaque Ahmed May 4 '17 at 19:36
24

The canonical check for WP-CLI used in the majority of plugins and specifically mentioned in the docs is to check WP_CLI is defined and set to true:

if ( defined( 'WP_CLI' ) && WP_CLI ) {
    // Do WP-CLI-specific things.
}

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.