Using wp-cli for Fun and Profit

Using wp-cli for Fun and Profit

Tutorial Details
  • Program: wp-cli
  • Version: 0.5
  • Difficulty: Intermediate
  • Estimated Completion Time: 20 minutes

See how you can perform common WordPress tasks faster or even automate them by using the power of bash.


What Is wp-cli?

wp-cli is a tool for controlling WordPress through a console window.

When the WordPress admin interface is so beautiful and easy to use, the natural question is: why would you ever use a command-line interface?

There are two main reasons:

  • The keyboard is faster than the mouse – For power users, typing a command can be orders of magnitude faster than pressing a button in a web browser.
  • Scripting – You can put several commands in a text file and have it executed automatically.

In this tutorial I’m going to give you a taste of what wp-cli is good for.


Installing wp-cli

Before using it, you’ll need a few things:

  1. UNIX-like shell – If you’re on a Mac or on Linux, you can run wp-cli on your local machine. If you’re on Windows, you can log into your Linux server via Putty and install wp-cli there.

  2. PHP 5.3+ and the php-cli utility – You can see if you have these by running the following command:

    php -v
  3. Git – This is what we’ll use to install and update wp-cli.

The wp-cli project is still in it’s infancy, so the best way to stay on top of recent versions is by cloning it from github:

git clone --recurse-submodules git://github.com/andreascreten/wp-cli.git ~/git/wp-cli
cd ~/git/wp-cli
sudo utils/build-dev

~/git/wp-cli is the directory where wp-cli will be installed. Feel free to change it to whatever you want.

That’s it. Now the wp command should be available:

cd /var/www/public_html/wordpress
wp
`wp` output

On Multisite

If you want to use wp-cli on a multisite install, you’ll have to decide which blog you want to operate on:

wp --blog=myblog.mynetwork.com

To avoid having to pass the --blog parameter for each command, you can store it in a specially-named file:

echo 'myblog.mynetwork.com' > wp-cli-blog

wp-cli will read that file if there’s no --blog parameter.


Handling Core

First, let’s see what version of WordPress we’re dealing with:

wp core version --extra
`wp core version` output

To perform an update, you just need to write:

wp core update
`wp core update` output

Handling Plugins

Let’s see what plugins we have installed:

wp plugin status
`wp plugin status` output

Huh, it seems there’s an update available for Akismet. Let’s install it:

wp plugin update akismet
`wp plugin update` output

Now let’s install and activate a plugin from wordpress.org:

wp plugin install google-sitemap-generator --activate
`wp plugin install` output

Also, you can install the development version of a plugin:

wp plugin install google-sitemap-generator --activate --dev

Oh, and look, there’s a new command available now:

wp google-sitemap
`wp sitemap help` output

We can quickly switch a plugin from active to inactive and vice-versa:

wp plugin toggle google-sitemap-generator
`wp plugin toggle` output

This is a good way to debug activation hooks.

Similarly, you can run a plugin’s uninstall procedure without deleting the plugin files:

wp plugin uninstall google-sitemap-generator

And, of course, you can delete the plugin as well:

wp plugin delete google-sitemap-generator

Handling Themes

We have a few commands for working with themes too:

wp theme status
`wp theme status` output

Unlike plugins, you can only have a single theme running at a time, so activating a theme will automatically “deactivate” the previous one:

wp theme activate twentyten

And here’s a little trick to go into the directory of a particular theme:

cd $(wp theme path twentyeleven)

Generating Data

If you’re writing a theme and you want to style the pagination, you’re going to need a lot of posts. Here’s the quickest way to get them:

wp generate posts --count=1000
`wp generate posts` output

If you want to style a list of users, you can generate some of them too:

wp generate users --role=author
`wp generate users` output

You can also create individual users:

wp user create stan stan@company.com
`wp user create` output

Creating Export Files

You might want to periodically export your content to a WXR file.

wp export --path=./ --user=admin
`wp export` output

You can pass additional parameters to limit what content is exported, such as --category, --start_date etc.


Changing Options on the Fly

There are straightforward commands for CRUD operations on options:

wp option get permalink_structure
wp option add foo bar
wp option delete foo

You don’t want to do this on a regular basis, as most options are constrained to certain values. But it can come in handy in scripts.


Database Operations

If you want to make a backup of the database, just write:

wp db dump
`wp db dump` output

Or perhaps you need to do a quick query to find when the last post was published:

wp db query "SELECT MAX(post_date) from wp_posts WHERE post_type = 'post' AND post_status = 'publish'"

Opening an interactive MySQL session to do some diagnostics is just as easy:

wp db cli

Running Arbitrary Code

Sometimes, the only way to tell wp-cli what you want is by describing it in PHP code:

wp eval-file do-my-laundry.php

With the above command, wp-cli will first load WordPress and then load and execute your PHP file.

This is useful in deploy scripts or for other complex actions that can’t be achieved using built-in commands.

You can also pass PHP code inline:

wp eval 'echo WP_CONTENT_DIR;'

Creating Your Own Commands

Believe it or not, wp-cli is written mostly in PHP. Each command is a class, with each method representing a subcommand.

The neat thing is that you can make your own class, put it in a plugin and wp-cli will automatically recognize it as one of it’s own. A detailed tutorial for creating commands is available in the project wiki.


Conclusion

I hope I’ve convinced you to at least give wp-cli a try. If you’ve found a bug or if you have a feature request, consider opening an issue.

Have an interesting use case for wp-cli? Please share it in the comments below.

Note: Want to add some source code? Type <pre><code> before it and </code></pre> after it. Find out more
  • http://codeseekah.com Gennady

    This is absolutely incredible and, unsurprisingly, appears to be very well-made. Will play around with it as soon as possible and review it in a couple of days. The extensibility of the tool is something to be excited about. I’m sure wp-cli is bound to be the Swiss army knife of all WordPress administrators and developers.

  • http://www.customicondesign.com/ custom icon design

    It’s my first time to notice the wp-cli, I will review it and look it weather is useful to me. many thanks.

  • http://sandeshghimire.com.np Sandesh Ghimire

    Wp-cli is quite handy. I suggest you all, to give a try. thanks for sharing

  • Pingback: Using wp-cli for Fun and Profit | Shadowtek | Hosting and Design Solutions

  • http://thomasgbennett.com Thomas Bennett

    This is great. I’m betting I could set it up to run through all domains on a server, back up the database and run these necessary upgrades. Saving a bunch of time each month…

  • http://webmastersintexas.com Jerry Lee

    I would love to use this, but am having issues cloning it into my (hostgator) Linux VPS server. It is saying unable to connect a socket, (Connection timed out).
    Any ideas?

    • http://scribu.net/ scribu

      @Jerry Lee: Maybe try using the https:// protocol:

      git clone –recurse-submodules https://github.com/andreascreten/wp-cli.git

    • http://thomasgbennett.com Thomas Bennett

      Jerry, are you able to run other git commands? Are other clones working? Shoot your commands over to have a look.

      • http://www.facebook.com/profile.php?id=100003406007116 Ratnasari

        I keep getting this error when calinlg the .GetUserBlogs() CookComputing.XmlRpc.XmlRpcIllFormedXmlException: Response from server does not contain valid XML.Any ideas on why that might be?ThanksKaos

  • http://thomasgbennett.com Thomas Bennett

    I’m getting “Error: This does not seem to be a WordPress install. Try running `wp core download`.” although I’m definitely in a WordPress directory? I’ve also tried in the install folder.

    I’m on Media Temple. Any help?

    • http://scribu.net/ scribu

      Maybe the files are not readable. Here’s the check that wp-cli does to find the wp install:

      https://github.com/andreascreten/wp-cli/blob/master/src/php/wp-cli/wp-cli.php#L34

      • http://thomasgbennett.com Thomas Bennett

        Then how would I get this?

        -bash-3.2# wp core download
        Downloading WordPress…
        sh: /curl: No such file or directory
        sh: /unzip: No such file or directory
        sh: /mv: No such file or directory
        sh: /rm: No such file or directory
        Success: WordPress downloaded.

        But nothing is downloaded of course.

        • http://scribu.net/ scribu

          The `wp core download` command is the only one that doesn’t require a WP install.

          The errors you’re getting are really strange, as if bash doesn’t recognize those basic commands.

          • http://thomasgbennett.com Thomas Bennett

            My Media Temple server had php safe_mode turned On, which adds a forward slash before the commands when they are run this way, with quotes around them. With a little help, I found that exec(` code `) worked and then was able to turn safe_mode off in php.ini for the fix.

  • Nick

    Very cool!

    Is it also possible that I can write a batch file with commands of standard stuff I do with each fresh WP install, so that it does that all automatically? That’d be really great!

  • http://vsellis.com Scott

    Nick, I’ve been considering the same thing so seeing Scribu’s post just made my day, a big chunk of the work is now done. Can’t wait to dig in an play with this. Great work here and thanks or sharing… this has been sorely needed for a while!

  • http://www.quentin-ravinet.fr Quentin

    A good one, but I think I’m not Geek enough !

  • http://tinywp.in Pothi Kalimuthu

    This is really cool stuff. I love the fun doing these things on command line. Highly appreciate your work on this!

  • http://lazaac.com lazaac

    thanks it’s awesome!!

  • wayno

    This lools like a real timesaver. Thanks, I look forward to implementing it.

  • Pingback: BlogBuzz February 25, 2012

  • http://thedev.in Devin Clark

    I am getting “Error establishing a database connection” on all my local sites with wp-cli. Any ideas?
    Here is what I get

  • Pingback: WP Auto Content Generator Script | Toko Ceban

  • Pingback: wp-cli – Introduction, Usage « « rtCafe rtCafe

  • http://vsellis.com Scott Ellis

    In case this helps anyone out… in order to install on my Media Temple dev server I had to change the clone command slightly since I keept getting an error : error: unknown option `recurse-submodules’

    Command Change

    From:
    git clone –recurse-submodules git://github.com/andreascreten/wp-cli.git ~/git/wp-cli

    To:
    git clone –recursive git://github.com/andreascreten/wp-cli.git ~/git/wp-cli

  • http://scribu.net/ scribu

    Hey, wp-cli has a new home: http://github.com/wp-cli/wp-cli

    There is where you cand find the latest version, report issues etc.

  • http://gabeherbert.com Gabe

    I’ve been wanting something like this!

    I’m using DreamHost shared hosting and can’t sudo. Is there a workaround?

    Thanks!

  • Pingback: #wcsea: WordPress at the Command Line | danielbachhuber

  • TC

    I’m running into an issue that I wanted to bring up here to see if perhaps there was more information that you have on the issue.

    I’m able to get a status list of plugins and their status by doing the following

    $ wp plugin status (this creates a list showing a few that need to be updated “UA” “UI”)

    when I try to update wordpress-seo (which shows a status of “UI”) via this command

    $ wp plugin update wordpress-seo

    I get the following…

    “Warning: up_to_date”

    …when I try to update breadcrumb-navxt (showing a status of “UA”)

    $wp plugin update breadcrumb-navxt

    again I get…

    “Warning: up_to_date”

    …is this a known issue? Am I doing something wrong? Any help/guidance you are able to lend is greatly appreciated.

  • shawn

    I have 300+ WP installs on a dedicated server. They are not tied together in multisite. I’ve worked through putty to do some simple server commands, so I do have full access.

    Can I still install wp-cli on my server, and modify/update “all” of my WP installs/plugins?

    We’re planning on moving these to a multi-site WP install – since we personally manage every one of these installs, but that’s going to take ages.

    • http://wp.envato.com/ Japh Thomson
      Staff

      Hi Shawn, I think it’s worth mentioning that in some cases there are other solutions that will work just as well.

      For example, you could use InfiniteWP (which is free) to update/modify all your installs. Also, migration could be done without too much hassle using a tool like BackupBuddy (which isn’t free).

      I’m not promoting either of these, just mentioning that if you don’t have the option of using wp-cli, there are other good alternatives too.

      • http://aghdesigns.net Andy

        Is there a way to do all the InfiniteWP does with the command line? I just want to say “Good Bye” to the mouse.

        Thanks in advance.
        Andy

  • http://icustomizethesis.com Puneet Sahalot

    That’s interesting!
    How about creating backups and pushing them to other server / Dropbox / AmazonS3 ?

  • Pingback: Bookmarks for December 14th | Chris’s Digital Detritus

  • Pingback: Recap It’s Tool Time 4 Tools You Cannot… | Portland WordPress Meetup