WordPress is a powerful content management system, but as your site grows, managing it can become time-consuming. This is where WP-CLI (WordPress Command Line Interface) comes in handy. WP-CLI allows you to manage WordPress from the command line, opening up a world of automation possibilities. In this guide, we’ll explore how to create custom automation scripts for WordPress using WP-CLI.
What is WP-CLI?
WP-CLI is a command-line tool for managing WordPress installations. It allows you to perform many tasks that you would typically do through the WordPress admin panel, but much faster and more efficiently.
Why Use WP-CLI for Automation?
- Speed: Command-line operations are typically faster than GUI interactions.
- Bulk Actions: Easily perform actions on multiple sites or posts.
- Scripting: Automate repetitive tasks with custom scripts.
- Remote Management: Manage WordPress sites without using a web browser.
- Integration: Incorporate WordPress management into your existing workflows.
Setting Up WP-CLI
Before we start creating scripts, let’s ensure WP-CLI is properly set up:
- Open your terminal or SSH into your server.
- Run the following commands:
curl -O https://raw.githubusercontent.com/wp-cli/builds/gh-pages/phar/wp-cli.phar
chmod +x wp-cli.phar
sudo mv wp-cli.phar /usr/local/bin/wp
- Verify the installation by running:
wp --info
If you see information about WP-CLI, you’re good to go!
Basic WP-CLI Commands
Before we dive into custom scripts, let’s review some basic WP-CLI commands:
wp core version
: Check WordPress versionwp plugin list
: List installed pluginswp theme activate twentytwentyone
: Activate a themewp post create --post_type=post --post_title='Hello World' --post_status=publish
: Create a new post
Creating Custom Automation Scripts
Now, let’s create some custom automation scripts using WP-CLI:
1. Bulk Update Plugins
Create a file named update_plugins.sh
:
#!/bin/bash
# Navigate to WordPress directory
cd /path/to/your/wordpress
# Update all plugins
wp plugin update --all
# Send email notification
echo "All plugins have been updated." | mail -s "WordPress Plugin Update" your@email.com
Make the script executable:
chmod +x update_plugins.sh
Run the script:
./update_plugins.sh
2. Create Multiple Posts from a CSV File
First, create a CSV file named posts.csv
:
Title,Content,Category
First Post,This is the content of the first post,General
Second Post,This is the content of the second post,News
Third Post,This is the content of the third post,Technology
Now, create a script named create_posts.sh
:
#!/bin/bash
# Navigate to WordPress directory
cd /path/to/your/wordpress
# Read CSV and create posts
while IFS=',' read -r title content category
do
wp post create --post_type=post --post_title="$title" --post_content="$content" --post_category="$category" --post_status=publish
done < posts.csv
Run the script:
./create_posts.sh
3. Backup WordPress
Create a script named backup_wordpress.sh
:
#!/bin/bash
# Set variables
BACKUP_DIR="/path/to/backup/directory"
SITE_NAME="mysite"
DATE=$(date +"%Y-%m-%d")
# Navigate to WordPress directory
cd /path/to/your/wordpress
# Create backup directory
mkdir -p $BACKUP_DIR/$SITE_NAME-$DATE
# Backup database
wp db export $BACKUP_DIR/$SITE_NAME-$DATE/database.sql
# Backup files
wp core download --path=$BACKUP_DIR/$SITE_NAME-$DATE/wordpress --skip-content
cp -R wp-content $BACKUP_DIR/$SITE_NAME-$DATE/wordpress/
# Compress backup
tar -czf $BACKUP_DIR/$SITE_NAME-$DATE.tar.gz -C $BACKUP_DIR $SITE_NAME-$DATE
# Remove uncompressed backup
rm -rf $BACKUP_DIR/$SITE_NAME-$DATE
# Notify
echo "Backup completed: $SITE_NAME-$DATE.tar.gz" | mail -s "WordPress Backup Completed" your@email.com
4. Clean Up Old Post Revisions
Create a script named cleanup_revisions.sh
:
#!/bin/bash
# Navigate to WordPress directory
cd /path/to/your/wordpress
# Delete post revisions
wp post delete $(wp post list --post_type='revision' --format=ids) --force
# Optimize database
wp db optimize
echo "Post revisions cleaned up and database optimized."
5. Generate a Content Audit Report
Create a script named content_audit.sh
:
#!/bin/bash
# Navigate to WordPress directory
cd /path/to/your/wordpress
# Generate report
echo "Content Audit Report" > content_audit.txt
echo "===================" >> content_audit.txt
echo "" >> content_audit.txt
echo "Total Posts: $(wp post list --post_type=post --format=count)" >> content_audit.txt
echo "Posts without categories: $(wp post list --post_type=post --format=count --category='')" >> content_audit.txt
echo "Posts without tags: $(wp post list --post_type=post --format=count --tag='')" >> content_audit.txt
echo "Posts without featured images: $(wp post list --post_type=post --format=count --meta_key=_thumbnail_id --meta_compare='NOT EXISTS')" >> content_audit.txt
echo "" >> content_audit.txt
echo "Top 5 categories by post count:" >> content_audit.txt
wp term list category --format=csv --fields=name,count | sort -t',' -k2 -nr | head -n 5 >> content_audit.txt
echo "Content audit report generated: content_audit.txt"
Advanced WP-CLI Techniques
Using WP-CLI in PHP Scripts
You can also use WP-CLI commands in PHP scripts. Here’s an example:
<?php
// Check if this is a CLI request
if (php_sapi_name() !== 'cli') {
die('This script can only be run from the command line.');
}
// Load WordPress
require_once('wp-load.php');
// Use WP_CLI
WP_CLI::run_command(array('post', 'list', '--format=csv'));
Save this as wp-cli-php-script.php
and run it with:
wp eval-file wp-cli-php-script.php
Creating Custom WP-CLI Commands
You can extend WP-CLI with your own custom commands. Create a file named custom-cli-command.php
in your theme or plugin:
<?php
if ( ! class_exists( 'WP_CLI' ) ) {
return;
}
/**
* Implements example command.
*/
class Custom_CLI_Command {
/**
* Prints a greeting.
*
* ## OPTIONS
*
* <name>
* : The name of the person to greet.
*
* ## EXAMPLES
*
* wp custom greet John
*
* @when after_wp_load
*/
function greet( $args, $assoc_args ) {
list( $name ) = $args;
WP_CLI::success( "Hello, $name!" );
}
}
WP_CLI::add_command( 'custom', 'Custom_CLI_Command' );
Now you can use your custom command:
wp custom greet John
Best Practices for WP-CLI Automation
- Use Version Control: Keep your scripts in a version control system like Git.
- Error Handling: Include error checking and handling in your scripts.
- Logging: Implement logging to track script actions and errors.
- Dry Run: For destructive operations, include a “dry run” option to preview changes.
- Modularity: Break complex scripts into smaller, reusable functions.
- Security: Be cautious with scripts that modify your WordPress installation. Always validate inputs.
Troubleshooting Common WP-CLI Issues
- “wp: command not found”: Ensure WP-CLI is properly installed and in your system’s PATH.
- Permission Errors: Make sure you have the necessary permissions to run WP-CLI and modify WordPress files.
- Database Connection Issues: Verify your wp-config.php file has correct database credentials.
- Memory Limits: If you encounter memory errors, you may need to increase PHP’s memory limit.
Frequently Asked Questions
Q1: Can I use WP-CLI on shared hosting?
A: It depends on your host. Some shared hosts support WP-CLI, while others don’t. Check with your hosting provider.
Q2: Is it safe to use WP-CLI for production sites?
A: Yes, when used correctly. Always test scripts on a staging site first and ensure you have backups.
Q3: Can WP-CLI handle multisite installations?
A: Yes, WP-CLI has specific commands for managing WordPress multisite networks.
Q4: How often should I run maintenance scripts?
A: It depends on your site’s needs. For example, you might run backup scripts daily, but cleanup scripts weekly.
Q5: Can I schedule WP-CLI scripts to run automatically?
A: Yes, you can use cron jobs to schedule your WP-CLI scripts to run at specific intervals.
Conclusion
WP-CLI is a powerful tool for WordPress automation, allowing you to create custom scripts that can significantly streamline your WordPress management tasks. By mastering WP-CLI, you can save time, reduce errors, and manage your WordPress site(s) more efficiently.
Remember to always test your scripts in a safe environment before running them on a live site. With practice, you’ll be able to create increasingly sophisticated automation workflows tailored to your specific WordPress needs.
Happy scripting!