How can I run a wp cli command when a wordpress hook is called on my website.
On user registration hook, I would like to run a wp cli command to activate a license.
How can I run a wp cli command when a wordpress hook is called on my website.
On user registration hook, I would like to run a wp cli command to activate a license.
Share Improve this question edited Mar 12, 2020 at 14:09 Toffee 4332 silver badges7 bronze badges asked Mar 11, 2020 at 18:26 Eko SetyantoEko Setyanto 111 silver badge1 bronze badge 2- 3 WP ClI has it's name suggests is a command line utility. It's not made to be run from php. Consider editing your question further, add some more information on what you are trying, does it involve a database operation, a file operation, a post request? – Toffee Commented Mar 12, 2020 at 12:57
- @Toffee "It's not made to be run from php" - the WP CLI is php so I guess you mean it's not made to be run through an HTTP request. But that's not the point - he is of course only asking how to trigger the CLI command through a browser request - which is completely valid if you have some long-running process that is not fit to run as part of an HTTP request. – TheStoryCoder Commented Mar 21, 2022 at 9:35
2 Answers
Reset to default 1Depends on what you want to do. If you want to run the PHP code that's behind the WP-CLI code you might consider looking at https://github/wp-cli/entity-command
Maybe you don't actually need WP-CLI but the corresponding code behind it. Most WP-CLI commands have Wordpress equivalents. For example of what I was trying to do today, the wp menu create "My Menu"
command is defined here:
https://github/wp-cli/entity-command/blob/master/src/Menu_Command.php. (It was much easier to find documentation for WP-CLI for this because 99% of results for Wordpress describe how to do it via the admin panel.)
Basically it just uses the WP function:
65: $menu_id = wp_create_nav_menu( $args[0] );
So > wp menu create "My Menu"
on the commandline is roughly equivalent to wp_create_nav_menu('My Menu')
in a functions.php
file.
Similarly, the plugin command would be addressed as a WP-CLI extension command defined in Plugin_Command.php which uses the Wordpress command activate_plugin(). If you want to know the WP version of the WP-CLI command you could look it up yourself or include the specific command you want to know in your question.
You can use the PHP exec() function to run wp-cli commands.
Example: <?php exec('wp core download'); ?>
Use with care. Further reading:
https://www.php/manual/en/function.exec.php