Introduction to WP-CLI
WP-CLI is a command-line tool for managing WordPress sites. It helps developers and site administrators automate tasks and perform bulk operations efficiently.
Installation and Setup
- Install WP-CLI on your server:
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 installation:
wp --info
Essential Commands
Core Management
Update WordPress core:
wp core update
Check current version:
wp core version
Plugin Management
Install and activate a plugin:
wp plugin install plugin-name --activate
Update all plugins:
wp plugin update --all
List all plugins with status:
wp plugin list
Theme Management
Install and activate a theme:
wp theme install theme-name --activate
Update all themes:
wp theme update --all
Database Operations
Export database:
wp db export backup.sql
Import database:
wp db import backup.sql
Search and replace URLs (useful for migrations):
wp search-replace 'old-domain.com' 'new-domain.com'
Content Management
Create a new post:
wp post create --post_type=post --post_title='New Post' --post_status=draft
List users:
wp user list
Best Practices
- Always backup before major operations:
wp db export backup_$(date +%Y%m%d).sql
- Use
--dry-run
flag to test commands:
wp search-replace 'old' 'new' --dry-run
- Create aliases for common commands in your
.bashrc
:
alias wplu='wp plugin update --all'
Security Considerations
- Restrict WP-CLI access to authorized users
- Use SSH keys for remote access
- Keep WP-CLI updated
- Never run untrusted commands
Common Pitfalls
- Not checking server requirements
- Running commands in wrong directory
- Forgetting to backup before operations
- Not testing commands with
--dry-run
Useful Helper Tools
-
WP-CLI Power Tools: Extends WP-CLI functionality
-
WP-CLI Toolkit: Collection of useful commands
Time-Saving Tips
- Use command completion:
wp cli completion bash > wp-completion.bash
source wp-completion.bash
- Create custom commands for repetitive tasks:
wp scaffold command custom-command
- Use
--format=json
for scripting:
wp plugin list --format=json
Automation Examples
Create multiple posts with featured images:
for i in {1..5}; do
wp post create --post_title="Post $i" --post_status=publish
wp media import sample.jpg --post_id=$(wp post list --posts_per_page=1 --format=ids)
done
Bulk optimize database tables:
wp db tables --format=csv | tr ',' '\n' | xargs -I % wp db query "OPTIMIZE TABLE %"
Remember to always test commands in a development environment first and maintain regular backups of your site.
These examples should give you a solid foundation for using WP-CLI effectively in your WordPress development workflow.