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

admin2025-01-07  9

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.

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.

Share Improve this question edited Sep 8, 2018 at 16:31 cjbj 15k16 gold badges42 silver badges89 bronze badges asked Sep 8, 2018 at 16:05 Youichi OkadaYouichi Okada 1236 bronze badges
Add a comment  | 

2 Answers 2

Reset to default 2

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.

Had this question today

You can use the WP-CLI internal API for this. Your plugin or theme can call

WP_CLI::runcommand( $command, $options = [] )

You can find more information on this here: https://make.wordpress.org/cli/handbook/references/internal-api/wp-cli-runcommand/

Note: As already stated there is a possibility that the server may not have WP-CLI installed but you can run a check for the WP_CLI constant at runtime like:

if ( defined( 'WP_CLI' ) && WP_CLI ) {
    // Do WP-CLI stuff
}

Edit: This is actually wrong. Thanks to @bosco for helping point this out. As he mentions in the comments the WPCLI definition is not loaded on requests, so it is far better to directly use the APIs available in the WordPress session. In OPs case of wanting to use subcommands from other plugins I see how using an already created plugin command would be helpful especially if there is not a hook for it but it seems using wpcli for this would not work unless you want to use exec or procopen which could be blocked on a shared hosting environment

转载请注明原文地址:http://conceptsofalgorithm.com/Algorithm/1736251974a9.html

最新回复(0)