主题为:未捕获错误的WP-CLI:找不到‘WP_CLI’类

时间:2017-01-17 作者:Julie

已更新::

在现有wordpress主题中添加自定义cli命令时出现问题。当我跑步时wp --info 我得到以下信息:

PHP binary: /usr/local/Cellar/php70/7.0.13_6/bin/php
PHP version:    7.0.13
php.ini used:   /usr/local/etc/php/7.0/php.ini
WP-CLI root dir:    phar://wp-cli.phar
WP-CLI packages dir:    
WP-CLI global config:   
WP-CLI project config:  /Users/julie/isl-site/isl-site/wp-cli.yml
WP-CLI version: 1.0.0
但是,当我在主题/函数中注册示例命令时。php

function foo_command( $args ) {
WP_CLI::success( $args[0] );
}
WP_CLI::add_command( \'foo\', \'foo_command\' );
我发现以下错误:

Uncaught Error: Class \'WP_CLI\' not found in /my-site/public/wp-content/themes/my-theme/lib/theme-functions.php:278
Stack trace:
15:23:29 web.1    | #0 /Users/julie/my-site/public/wp-content/themes/my-theme/functions.php(36): require_once()
15:23:29 web.1    | #1 /Users/julie/my-site/public/wp/wp-settings.php(387): include(\'/Users/julie/...\')
15:23:29 web.1    | #2 /Users/julie/my-site/public/wp-config.php(212): require_once(\'/Users/julie/...\')
15:23:29 web.1    | #3 /Users/julie/my-site/public/wp/wp-load.php(44): require_once(\'/Users/julie/...\')
15:23:29 web.1    | #4 /Users/julie/my-site/public/wp/wp-blog-header.php(13): require_once(\'/Users/julie/...\')
15:23:29 web.1    | #5 /Users/julie/my-site/public/index.php(5): require(\'/Users/julie/...\')
15:23:29 web.1    | #6 {main}
15:23:29 web.1    |   thrown in /Users/julie/my-site/public/wp-content/themes/my-theme/lib/theme-functions.php on line 278
对如何解决此问题有何见解?

1 个回复
SO网友:Daniel Bachhuber

您需要将您的声明包装在class_exists() 检查:

function foo_command( $args ) {
    WP_CLI::success( $args[0] );
}
if ( class_exists( \'WP_CLI\' ) ) {
    WP_CLI::add_command( \'foo\', \'foo_command\' );
}
这样,仅当WP_CLI 类存在-因为WP_CLI 类仅在WP-CLI运行时存在。