HEWeb #DPC9: How to extend WP-CLI for fame and fortune

Tuesday, October 10th, 2023

Tuesday, October 10, 2023, 1:45 PM – 2:30 PM EDT
Paul Gilzow – Platform.sh

You’re using the WordPress Command Line Interface (WP-CLI) to automate your workflows, WordPress site set-ups, adding users, etc. You’ve even added it to your CI/CD pipelines to automate behavioral testing and configuration of your testing environments. Recently you added a new plugin to your site that dramatically improves the functionality, only to discover that its data is locked out of WP-CLI, completely unavailable. Do you bail on the plugin and look for another one that is more compatible with WP-CLI? Or do you take matters into your own hands?

In this session, we won’t be discussing the basics of WP-CLI, though we will do a brief introduction. Instead, we’ll be focusing on how we can extend it, adding our own commands and modifying it to accommodate our own, unique needs.

Notes:

  • Anatomy of a custom command
    • Build as a plugin and use: WP_CLI::add_command()
  • Where should we install?
    • New plugin (but must be avtive)
    • Established plugin or theme
    • However, plugins run late so you miss some of the hook activations
    • Must-use plugin
    • wp cli package (always active)
      • Can be a path to a git repo or a local folder
      • Requires a composed.json file
  • Adding help and desriptions
    • Use PHP doc block
    • Or, as part of the add_command array
  • Arguments
    • Allow 2 parameters when activated (positional and associative)
    • wp campus paul –subject=devops
    • Once set up, arguments are required by default. If you need them to be optional, the doc block needs to represent that.
  • You can create you own namespace, or add a subcommand to plugins, sites, etc..
    • wp wpcampus greet, wp wpcampus farewell
  • Reserved words (like ‘list’)
    • use @subcommand tag
  • WP CLI had a bunch of commands and its own API – you can run other wp cli commands
  • Avoid using other wp cli commands (they reload all wp guts in another session)
    • Just use the native functions

Leave a Reply

You know you want to...