# Rename a Shortcode Across All Content (WP-CLI)

> Adds a "wp rename-shortcode" command that changes every use of one shortcode tag to another in posts and pages, attributes and closing tags included, useful when switching plugins.

- Type: PHP
- Runs: Run everywhere
- Category: [Developer](https://wpide.com/library/category/developer/)
- Tags: wp-cli, shortcodes, migration
- Author: WPIDE Team
- Installs: 0
- Updated: 2026-10-28
- Page: https://wpide.com/library/cli-rename-shortcode/

## Code

```php
if ( ! defined( 'WP_CLI' ) || ! WP_CLI ) {
    return;
}

WP_CLI::add_command( 'rename-shortcode', function ( $args, $assoc_args ) {
    global $wpdb;

    list( $old, $new ) = array_map( 'sanitize_key', $args );
    if ( ! $old || ! $new || $old === $new ) {
        WP_CLI::error( 'Give two different shortcode tags.' );
    }

    // Matches [old ...], [old] and [/old] but not [old_more].
    $pattern = '/\[(\/?)' . preg_quote( $old, '/' ) . '(?=[\s\]\/])/';
    $rows    = $wpdb->get_results( $wpdb->prepare(
        "SELECT ID, post_content FROM {$wpdb->posts} WHERE post_type NOT IN ('revision') AND post_status NOT IN ('trash','auto-draft') AND post_content LIKE %s",
        '%[' . $wpdb->esc_like( $old ) . '%'
    ) );

    $changed = 0;
    foreach ( $rows as $row ) {
        $content = preg_replace( $pattern, '[$1' . $new, $row->post_content, -1, $count );
        if ( ! $count ) {
            continue;
        }
        $changed++;
        if ( ! empty( $assoc_args['yes'] ) ) {
            wp_update_post( array( 'ID' => (int) $row->ID, 'post_content' => wp_slash( $content ) ) );
        }
    }

    if ( empty( $assoc_args['yes'] ) ) {
        WP_CLI::log( sprintf( '%d posts use [%s] and would be updated. Add --yes to apply.', $changed, $old ) );
        return;
    }
    WP_CLI::success( sprintf( 'Renamed [%s] to [%s] in %d posts.', $old, $new, $changed ) );
}, array(
    'shortdesc' => 'Renames a shortcode tag in all content.',
    'synopsis'  => array(
        array( 'type' => 'positional', 'name' => 'old' ),
        array( 'type' => 'positional', 'name' => 'new' ),
        array( 'type' => 'flag', 'name' => 'yes', 'optional' => true ),
    ),
) );
```

## Notes

Example "wp rename-shortcode old_button button --yes"; without --yes it only counts. Revisions are created so changes can be rolled back per post.

## How to use it

Install the free WPIDE plugin (https://wordpress.org/plugins/wpide/), find "Rename a Shortcode Across All Content (WP-CLI)" in its snippet library and add it in one click; or create a new PHP snippet in WPIDE (or any code snippets plugin) and paste the code above. More snippets: https://wpide.com/library/
