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.
Opens WPIDE on
Code
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 add this snippet
- Install WPIDE on your WordPress site (it is free) and open Code Snippets.
- Use snippet above adds it from the library in one click. Or copy the code into a new snippet with the same code type.
- It is added inactive: review the code and settings, then switch it on.