Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Run WP-CLI using PHP

I've installed WP-CLI on the Mac and my next step is to execute WP-CLI commands using PHP script.

I've tried to implement it the following way but I do not see anything happening. Can someone please look at my code and tell me that what I'm doing wrong?

define( 'WP_CLI_ROOT', '/usr/local/bin/wp' );
include WP_CLI_ROOT . '';
$output = shell_exec("wp --info");
echo "<pre>".$output."</pre>";

Do I need to configure and setup wp-cli with my PHP files?

Also, when I type wp --info on my terminal the following information comes up. Nothing is appearing beside the Package Dir & global config. do I also need to make adjustments to wp-cli?

MAC-00343:htdocs mike$ wp --info
PHP binary: /usr/bin/php
PHP version:    5.6.30
php.ini used:   
WP-CLI root dir:    phar://wp-cli.phar
WP-CLI vendor dir:  phar://wp-cli.phar/vendor
WP_CLI phar path:   /Users/mike/Docker/xamp/www/wordpress_wwws/htdocs
WP-CLI packages dir:    
WP-CLI global config:   
WP-CLI project config:  
WP-CLI version: 1.3.0

Any help or suggestions will be much appreciated.

Thanks

like image 509
WKL Avatar asked Nov 23 '25 15:11

WKL


1 Answers

The problem is your wp cli aren't in the path environment variable, you should add your wp cli root to the path environment as following, hopefully this is helpful. For reference all wp cli command, visit the url - https://wpcommands.com

<?php
$saved = getenv("path");    // get the value of PATH environment variable and save current value
$newld = "/usr/local/bin";          // extra paths to add - in this case, it should be your wp cli root
if ($saved)
{
    $newld .= ":$saved";
}
// append old paths if any
putenv("path=$newld");        // set new value

// exec wp cli command
$output = shell_exec("wp --info");
echo "<pre>".$output."</pre>";


?>
like image 64
Chung Nguyen Avatar answered Nov 25 '25 07:11

Chung Nguyen