Using xdebug with wp-cli

Sometimes when you want to profile something in WordPress using xdebug, it’s not quite as straightforward as just enabling the tool in php.ini and passing a query string parameter. Say for example that you’re wanting to test how expensive it is to delete a term in WordPress. Well, you can load the term page with the query string parameter in place, but then you still wind up posting data without the query string parameter. You have a few options that I know of:

  1. Turn on xdebug for every request and figure out which cachegrind file contains the bits you actually want to profile.
  2. Hack the code to add the query string to your post.
  3. Write a cookie that xdebug can use in place of the query string variable.

None of these options especially appeal to me. They just seem clumsy.

I’ve used wp-cli more and more lately to interact with WordPress installs. And of course wp-cli has commands for interacting with terms. So it’d be neat to be able to profile wp-cli commands using xdebug. Luckily, it turns out to be pretty easy to do.

First, get xdebug and wp-cli set up. Links above will point you to documentation for doing so. When I set xdebug up, the extension was added to apache’s php config but not to the cli version of php.ini, so I had to copy the relevant line (extension=/path/to/ from one php.ini to the other.

Now you just have to add the -dxdebug.profiler_enable=1 option to your call to php at the command line. With wp-cli, you’re not calling php directly at the command line, though, so you have to figure out how to get the option passed through to the actual call. It turns out that the bash script that wraps wp-cli has a handy argument named $WP_CLI_PHP_ARGS that you can use to pass php arguments.

So if you always want to use xdebug with wp-cli, you can just do something like this in your .bash_profile:

export WP_CLI_PHP_ARGS=-dxdebug.profiler_enable=1

But maybe you don’t always want to profile wp-cli. Doing so slows operations down a little, and it generates pretty big cachegrind files, especially for complex or long-running operations (for example, a simple wp term delete command that takes around 2 seconds was generating 5MB cachegrind files for me). To run xdebug with wp-cli only when I really wanted to and without having to remember to set or unset $WP_CLI_PHP_ARGS when I wanted to toggle, I just added these lines to my .bash_profile:

alias wp="export WP_CLI_PHP_ARGS=; $HOME/.wp-cli/bin/wp"
alias wpd="export WP_CLI_PHP_ARGS=-dxdebug.profiler_enable=1; $HOME/.wp-cli/bin/wp"

Now, if I want to generate cachegrind files to profile, I execute wpd instead of wp, and life is good.

Leave a Reply


You are commenting using your account. Log Out /  Change )

Google photo


Twitter picture


Facebook photo


Connecting to %s