keepcalculator

06 Numbers and Powers

Custom WP CLI Commands with Acorn

Card No. 06·50652 · Updated · Standard formula, shown below

This guide shows you how to write custom WP-CLI commands using Acorn, the Laravel framework for WordPress. You’ll learn to create commands that integrate with your Acorn application, allowing you to run custom scripts, interact with your models, and extend your workflow directly from the terminal. You’ll need a working WordPress installation with Acorn installed and a basic understanding of PHP and the command line.

What You’ll Need

  • A WordPress site with Acorn installed and activated (usually via Composer and a theme or plugin).
  • WP-CLI installed on your server or local environment.
  • Access to your theme or plugin files where Acorn is set up.
  • Basic knowledge of PHP, Composer, and the command line.

Step-by-Step

  1. Locate your Acorn application directory. Typically, this is the app folder inside your theme or plugin. You’ll see subdirectories like Console, Http, and Models. If the Console directory doesn’t exist, create it.
  2. Create a command class. Inside the Console directory, create a new PHP file, for example SayHello.php. This class will extend Illuminate\Console\Command.
  3. Define the command signature. In your class, set the $signature property to define the command name and its arguments/options. For example: protected $signature = 'hello:world {name? : The name to greet}'; This creates a command wp hello:world with an optional name argument.
  4. Set the description. Add a protected $description = 'Say hello to the world or a specific person.'; property to describe what the command does.
  5. Write the handle method. This is where the command logic goes. The method is called when the command runs. Use the $this object to interact with the console (e.g., $this->argument('name'), $this->option('option'), $this->info('...'), $this->error('...')).
  6. Register the command with Acorn. In your Acorn application service provider (usually app/Providers/AppServiceProvider.php), add the command to the commands array in the register method. For example: $this->commands([\App\Console\SayHello::class]);
  7. Clear cached Acorn files (if needed). Run wp acorn optimize:clear to clear any cached config or routes, ensuring your new command is picked up.
  8. Test your command. Run wp hello:world from your terminal in the WordPress root directory. You should see the output from your handle method.
  9. Use Acorn features inside your command. You can now use Eloquent models, the database, and other Laravel services. For example, \App\Models\Post::all() to fetch posts, or Cache::put('key', 'value', 60) to store data.
  10. Handle arguments and options. Access arguments via $this->argument('name') and options via $this->option('option'). You can also use array arguments/options and prompts with $this->ask() or $this->confirm().

Common Mistakes

  • Forgetting to register the command. The command class alone won’t be recognized by WP-CLI; you must add it to the commands array in a service provider.
  • Wrong namespace. Ensure the namespace in your command class matches the directory structure and the composer.json autoload settings. A mismatch will cause a “class not found” error.
  • Using echo instead of $this->line() or $this->info(). Using echo can break WP-CLI’s output formatting and may not respect flags like --quiet.
  • Not clearing the Acorn cache. If you have previously run wp acorn optimize, your new command might not be discovered until you clear the cache with wp acorn optimize:clear.
  • Incorrect command signature syntax. Make sure to use the correct format for arguments ({name}), optional arguments ({name?}), and options ({--option}). A typo here will cause the command to not be recognized.

Tips

  • Use type-hinting for dependency injection. In your handle method, you can type-hint any class, and Acorn’s container will automatically resolve it. For example, public function handle(MyService $service).
  • Leverage Laravel’s helpers. Use collect(), Str::, Arr::, and other Laravel helpers to write cleaner code.
  • Make commands testable. Keep your command logic thin and move business logic into service classes that can be unit-tested independently.
  • Use progress bars for long tasks. If your command processes many items, use $this->output->createProgressBar($count) to show progress.
  • Document your commands. Use the --help flag to test your command’s description and argument/option help text.

Troubleshooting

  • Command not found. Run wp list to see if your command appears. If not, check that the command is registered in the service provider, the class file is autoloaded (run composer dump-autoload), and the Acorn cache is cleared.
  • Class not found error. Verify the namespace and file location. Run composer dump-autoload to regenerate the autoloader.
  • Output not showing. Ensure you’re using $this->line(), $this->info(), $this->error(), etc., not echo or print_r.
  • Database errors. If your command uses the database, ensure your .env file has the correct database credentials and that the WordPress database is accessible. You may need to run wp acorn migrate if you have migrations.
  • Acorn not loaded. If you get errors about Acorn classes not found, make sure Acorn is properly installed and the wp acorn command works. Try running wp acorn list to see if the base commands are available.

Frequently Asked Questions

  • Can I use WP-CLI’s built-in functions like WP_CLI::success()? Yes, you can use the WP_CLI class directly, but it’s recommended to use Acorn’s output methods for consistency. You can also call WP_CLI::add_command() if you prefer the traditional approach, but Acorn’s registration is cleaner.
  • How do I pass arguments with spaces? Wrap them in quotes when calling the command, e.g., wp hello:world "John Doe".
  • Can I schedule my custom commands? Yes, you can use WP-Cron or a system cron job to run `wp your:command` at intervals. Acorn commands are just PHP scripts, so they work with any scheduler.
  • How do I make a command interactive? Use $this->ask(), $this->confirm(), $this->secret(), or $this->choice() to prompt the user for input during execution.
  • Can I use Eloquent models in my commands? Absolutely. Acorn loads the full Laravel framework, so you can use any model, query builder, or service as you would in a controller.
  • What if my command needs to run only on a specific environment? You can check app()->environment() or use the --env option when running the command to specify the environment.

Related

Method: the standard formula for this calculation, rounded as each result states. See how the calculators work or report an error.

More cards in this drawer

The whole Numbers and Powers drawer →