Automate WordPress with WP CLI
How long does it take you to install a new WordPress website?
Do you have a collection of plugins you constantly use for every WordPress website you install? Does the same go for themes?
What about some dummy data? Do you have to add some posts and pages every time?
What if you want to automate some commands on the admin panel (like custom cron jobs, replacing brand name, adding a list of users)?
In comes WP CLI
WP CLI is basically a power tool for WordPress developers.
It lets you do almost everything that you do on your WordPress admin panel from the command line, with some awesome extras.
To create a WP website:
</p>
<p>wp site create --slug="simpsons" --title="Simpsons Blog" --email="[email protected]" --private</p>
This will create a private website (not indexed) titled Simpsons Blog (slug is simpsons), where the admin's email is [email protected]
Scaffold
I just love this command! It lets you generate PHP code for creating post types, taxonomies, as well as themes & child themes!
Tip Time!
If you ever make changes to a WordPress theme you have,
never make them directly on the theme itself, if you do, after updating the theme your changes will often be gone! Plus that's not a good way of keeping with encapsulation.
Instead, create a child theme which "inherits" the design and functions of your parent theme and builds on top of them.
Scaffold has a command that lets you generate a child-theme with a single command:
wp scaffold child-theme kidsil --parent_theme=twentyfourteen
This would create a theme with the slug kidsil, whose parent theme is TwentyFourteen.
Export
I’d recommend running exports of your posts as a Cron Job, on top of normal DB & Website backups, WP exports take up less space, as well as don’t take as long to run.
It also takes less time to import them back to your website (depending on how much data you have).
The simplest export command (just exports everything):
wp export --dir=/tmp/
As you can see, this exports to /tmp/. The output XML file is named:
WEBSITE_NAME.wordpress.2014-09-25.0.xml
But if we’re running a Cron job every week, why should we copy the same posts again and again?
Let’s run a command that only gets last week’s posts (some bash magic over here):
wp export --start_date=$(date +"%Y-%m-%d" --date="-7 day")
Pretty neat right? All you have to do is run it as a Cron job and there you have it, Automatic backups!
There are a lot of very useful commands, for taxnomies, users, transients, widgets and sidebars to name a few. I definitely recommend digging into the wonderful documentation.
I hope I gave everyone a few ideas on how to potentially use WP CLI.
Until next week!