Tell me for any kind of development solution

Edit Template

Building Custom WordPress CLI Commands: A Guide to Task Automation

Tired of doing WordPress tasks manually or need to create Custom WordPress CLI Commands in WordPress? Creating custom WP-CLI commands can be a total game changer for developers looking to simplify their workflow. In this guide we’ll show you how to create custom WP-CLI commands to automate tedious tasks and boost your productivity.

As a custom command want to create your own plugin so explore this article.

What is Wp-CLI?

WP-CLI stands for WordPress Command Line Interface. It’s a set of commands to manage your WordPress installation without using a web browser. With WP-CLI you can update plugins, manage themes and import/export content quickly and efficiently also your any custom task. The ability to Custom WordPress CLI Commands takes this to the next level and allows you to create solutions for your specific needs.

Installing WP-CLI on Your System

Before diving into custom commands, let’s ensure you have WP-CLI properly installed:

1. Download the WP-CLI phar file:

curl -O https://raw.githubusercontent.com/wp-cli/builds/gh-pages/phar/wp-cli.phar

2. Make it executable and move it to your PATH:

chmod +x wp-cli.phar
sudo mv wp-cli.phar /usr/local/bin/wp

3. Verify the installation:

wp --info

Why Create Custom WordPress CLI Commands

Custom WP-CLI commands have many benefits:

  1. Time Saving: Automate tasks that would take hours to do manually
  2. Consistency: Do tasks the same way every time
  3. Batch Processing: Do bulk stuff
  4. Server Side: Run resource intensive tasks on the server
  5. Version Control: Easy to integrate with your workflow
  6. Documentation: Self documenting through command line help

Where to Implement Custom Commands

Content

  • Bulk post creation and editing
  • Custom taxonomies
  • Media library
  • Content migration between sites

Database

  • Custom backups
  • Data cleanup and optimization
  • Table maintenance
  • Data import/export

Site Maintenance

  • Security checks and updates
  • Performance optimization
  • Error log analysis
  • Configuration management

Practical Example: Creating a Custom WP-CLI Command

Let’s create a practical custom command that finds and replaces text across all posts:

<?php
/**
 * Custom WP-CLI command for bulk text replacement
 */
class Text_Replace_Command extends WP_CLI_Command {
    /**
     * Replaces specified text in all posts
     *
     * ## OPTIONS
     *
     * <search>
     * : Text to search for
     *
     * <replace>
     * : Text to replace with
     *
     * [--post-type=<type>]
     * : Post type to process (default: post)
     *
     * ## EXAMPLES
     *
     *     wp text-replace "old text" "new text"
     *     wp text-replace "old text" "new text" --post-type=page
     */
    public function replace( $args, $assoc_args ) {
        list( $search, $replace ) = $args;
        $post_type = \WP_CLI\Utils\get_flag_value( $assoc_args, 'post-type', 'post' );
        
        $posts = get_posts( array(
            'post_type' => $post_type,
            'posts_per_page' => -1,
        ) );

        $count = 0;
        foreach ( $posts as $post ) {
            if ( strpos( $post->post_content, $search ) !== false ) {
                $new_content = str_replace( $search, $replace, $post->post_content );
                wp_update_post( array(
                    'ID' => $post->ID,
                    'post_content' => $new_content
                ) );
                $count++;
            }
        }

        WP_CLI::success( "Replaced text in $count posts." );
    }
}

WP_CLI::add_command( 'text-replace', 'Text_Replace_Command' );

Command to run:

wp text-replace

Essential WP-CLI Methods for Custom Commands

Understanding the core WP-CLI methods is crucial for creating effective custom commands. Here are the most useful methods you’ll need:

1. Output Methods

WP_CLI::line()

Prints a line of text to the console without any formatting.

WP_CLI::line( 'Processing post ID: ' . $post->ID );

WP_CLI::success()

Displays a success message with green coloring.

WP_CLI::success( 'Successfully updated 25 posts!' );

WP_CLI::warning()

Shows a warning message in yellow.

WP_CLI::warning( 'Some posts could not be processed.' );

WP_CLI::error()

Displays an error message and halts execution by default.

if ( !$post ) {
    WP_CLI::error( 'Post not found!' );
}

2. Progress Tracking

WP_CLI::make_progress_bar()

Creates a progress bar for long-running operations.

$posts = get_posts(['posts_per_page' => -1]);
$progress = \WP_CLI\Utils\make_progress_bar( 'Processing posts', count($posts) );

foreach ( $posts as $post ) {
    // Process each post
    // ...
    $progress->tick();
}

$progress->finish();

3. User Interaction

WP_CLI::confirm()

Prompts the user for confirmation before proceeding.

class Database_Cleanup_Command extends WP_CLI_Command {
    public function clean( $args ) {
        WP_CLI::confirm( 'Are you sure you want to clean the database?', $args );
        // Proceed with cleanup
    }
}

WP_CLI::prompt()

Asks the user for input.

$email = WP_CLI::prompt( 'What is the admin email?' );

4. Data Formatting

WP_CLI\Utils\format_items()

Formats data into tables, CSV, JSON, or YAML.

class User_Stats_Command extends WP_CLI_Command {
    public function show() {
        $data = array(
            array(
                'user_id' => 1,
                'posts' => 15,
                'comments' => 45
            ),
            array(
                'user_id' => 2,
                'posts' => 10,
                'comments' => 30
            )
        );
       
        \WP_CLI\Utils\format_items( 'table', $data, array( 'user_id', 'posts', 'comments' ) );
    }
}

5. File System Operations

WP_CLI\Utils\get_flag_value()

Safely retrieves command-line flag values.

class Export_Command extends WP_CLI_Command {
    public function posts( $args, $assoc_args ) {
        $post_type = \WP_CLI\Utils\get_flag_value( $assoc_args, 'post-type', 'post' );
        $status = \WP_CLI\Utils\get_flag_value( $assoc_args, 'status', 'publish' );
    }
}

6. Debug and Logging

WP_CLI::debug()

Logs debug messages when –debug flag is used.

class Import_Command extends WP_CLI_Command {
    public function data( $args ) {
        WP_CLI::debug( 'Starting import process' );
        // Import logic here
        WP_CLI::debug( 'Import completed' );
    }
}

Advanced Usage With Custom Commands

1. Automated Workflows

  • Site cloning and migration
  • Environment specific configuration
  • Database sync
  • Asset optimization

2. Custom Analytics and Reporting

  • User engagement metrics
  • Content performance analysis
  • Error monitoring and alerts
  • SEO data collection

3. E-commerce Automation

  • Inventory management
  • Price updates
  • Order processing
  • Customer data analysis

Tips and Considerations

When creating custom WordPress CLI commands, remember:

1. Performance

  • Use batch for big operations
  • Show progress indicators
  • Consider memory limits

2. Error handling

  • Catch errors properly
  • Show meaningful error messages
  • Rollback mechanisms

3. Security

  • Validate user input
  • Check permissions
  • Protect sensitive operations

4. Documentation

  • Write command descriptions
  • Show examples
  • Document parameters and flags

Conclusion

Creating custom WordPress CLI commands is a must have skill for any WordPress developer looking to automate their workflow. By creating commands for your specific use case you can save a lot of manual work and get more productive.

Ready to start creating your own custom WP-CLI commands? Start with small automation tasks and gradually move to more complex ones. Always test your commands in a development environment first.

Share Article:

© 2025 Created by ArtisansTech