Run WP-CLI using PHP

Regarding the wp --info output, that makes sense. If you don’t have any packages installed (see wp package --help or a global configuration files (wp-cli.yml) then those items would be blank.

You can run the wp command from any location. If you’re anywhere within your website’s folder structure it will automatically detect the site you’re on by navigating up the folder tree until it finds a wp-config.php file.

If running wp from a location outside your site’s folder structure, you’ll have to specify the path, like this:

wp --path=/path/to/wordpress/site/ core version

As for executing commands from within PHP, this following works for me:

test.php

<?php
$output = shell_exec("wp --info");
echo "<pre>".$output."</pre>";
?>

running php test.php from the command line, I get:

PHP binary:    /usr/local/Cellar/php71/7.1.1_12/bin/php
PHP version:    7.1.1
php.ini used:   /usr/local/etc/php/7.1/php.ini
WP-CLI root dir:    phar://wp-cli.phar
WP-CLI vendor dir:  phar://wp-cli.phar/vendor
WP_CLI phar path:   /Users/shawnhooper
WP-CLI packages dir:    /Users/shawnhooper/.wp-cli/packages/
WP-CLI global config:
WP-CLI project config:
WP-CLI version: 1.3.0

Also there is quite a lengthy discussion on running WP-CLI commands from PHP in the project’s official GitHub repo. You might find this issue of interest: https://github.com/wp-cli/wp-cli/issues/1924

Leave a Comment