Is it possible to use WP-CLI in a plugin (or theme)?

Such as

  $ret = \WP_CLI::execute('plugin list');

I want to use some subcommands from other plugins.

WP-CLI is a command line interface to WP. So, it is used in a Unix shell environment. Plugins and themes are written in PHP (which itself also runs in a shell, usually Unix). So, to execute a WP-CLI command in a plugin you would have to pass it from PHP to the Unix shell. That may be done using the PHP function shell_exec.

So, the answer to the question 'is it possible?', is YES. However, the answer to the question 'should I be doing this?' is NO WAY. Here are some considerations:

  1. WP-CLI may not even be installed on the server the plugin/theme is used on, for instance because it is a Windows based server.

  2. Using shell_exec from a theme/plugin is a security risk, because of the powerful commands that are possible on the command line. Many providers block PHP from using shell_exec and other execution commands.

  3. Everything you can do through WP-CLI can be done in WP proper as well. After all, it is a gateway to WP and offers no additional functionality.

  • I don't plan to use exec or something. – Youichi Okada Sep 8 at 16:41
  • So, how are you planning to get the shell command out of the PHP environment? – cjbj Sep 8 at 16:42

Your Answer

 
discard

By clicking "Post Your Answer", you acknowledge that you have read our updated terms of service, privacy policy and cookie policy, and that your continued use of the website is subject to these policies.

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