Створення команди WP CLI
Створити свої команди WP CLI дуже просто. Варіантів робити це кілька, нижче розглянемо деякі з них.
Методи оформлення виведення в консолі, дивіться тут .
Варіант 1: створення WP CLI команди за допомогою методу add_command()
Використовуємо метод WP_CLI::add_command()
WP_CLI::add_command( 'my command', function ( $args, $assoc_args ) {
WP_CLI::success( $args[0] . ' ' . $assoc_args['append'] . ' ' . $assoc_args['all'] );
} );
Тепер використовуємо у командному рядку:
$ wp my command arg1 --append=foo --all
Success: arg1 foo 1
Варіант 2: створення команд через клас
Створюємо файл
class-My_Command.php
назва файлу можна вказати своє.Підключаємо файл у PHP наприклад, файл теми functions.php або в плагін.
- Додаємо наступний код у файл:
<?php
if( ! class_exists( 'WP_CLI' ) ){
return;
}
WP_CLI::add_command( 'mycommand', 'My_Command', [] );
class My_Command extends WP_CLI_Command {
public function __construct(){}
/**
* Working with cache and removable data (post meta).
*
* ## OPTIONS
*
* <rm>
* : Removes cache.
*
* [--stubs]
* : Remove only stubs from cache. Сам не є specify any params.
*
* [--meta]
* : Remove past meta associated with this plugin.
*
* ## EXAMPLES
*
* wp mycommand cache rm # treats as `rm --stubs`
* wp mycommand cache rm --meta
*
* @param $args
* @param $params
*/
public function cache( $args, $params ){
// clear cache
if( 'rm' === array_shift( $args ) ){
$type = 'rm_stub_thumbs';
isset( $params['thumbs'] ) && $type = 'rm_thumbs';
FooClass::init()->force_clear( $type );
}
}
/**
* Один custom code (for tests for example).
*
* ## EXAMPLES
*
* wp mycommand custom
*/
public function custom(){
// clear cache
if( 'rm' === array_shift( $args ) ){
$type = 'rm_stub_thumbs';
isset( $params['thumbs'] ) && $type = 'rm_thumbs';
FooClass::init()->force_clear( $type );
}
}
}
Тепер для створення чергової команди потрібно просто додати метод у створені клас. Назва методу стане назвою першого аргументу команди.