List Every Shortcode Used in Content (WP-CLI)
Adds a "wp shortcodes-in-use" command that scans all content and lists each shortcode tag found, how many posts use it and whether anything is still registered to handle it.
Opens WPIDE on
Code
if ( ! defined( 'WP_CLI' ) || ! WP_CLI ) {
return;
}
WP_CLI::add_command( 'shortcodes-in-use', function ( $args, $assoc_args ) {
global $wpdb;
$usage = array();
$last = 0;
do {
$rows = $wpdb->get_results( $wpdb->prepare(
"SELECT ID, post_content FROM {$wpdb->posts} WHERE ID > %d AND post_type NOT IN ('revision','attachment','nav_menu_item')
AND post_status NOT IN ('trash','auto-draft') AND post_content LIKE '%%[%%' ORDER BY ID LIMIT 500",
$last
) );
foreach ( $rows as $row ) {
$last = (int) $row->ID;
// Strip block comments so JSON in them is not mistaken for shortcodes.
$text = preg_replace( '/<!--.*?-->/s', '', $row->post_content );
if ( preg_match_all( '/\[([a-zA-Z][\w-]*)(?=[\s\]\/])/', $text, $matches ) ) {
foreach ( array_unique( $matches[1] ) as $tag ) {
$usage[ $tag ] = ( $usage[ $tag ] ?? 0 ) + 1;
}
}
}
} while ( count( $rows ) === 500 );
if ( ! $usage ) {
WP_CLI::success( 'No shortcodes found in content.' );
return;
}
arsort( $usage );
$items = array();
foreach ( $usage as $tag => $posts ) {
$items[] = array( 'shortcode' => $tag, 'posts' => $posts, 'status' => shortcode_exists( $tag ) ? 'registered' : 'missing' );
}
WP_CLI\Utils\format_items( $assoc_args['format'] ?? 'table', $items, array( 'shortcode', 'posts', 'status' ) );
}, array(
'shortdesc' => 'Lists shortcode tags used in content.',
'synopsis' => array(
array( 'type' => 'assoc', 'name' => 'format', 'optional' => true, 'default' => 'table', 'options' => array( 'table', 'csv', 'json' ) ),
),
) );
Notes
Tags marked "missing" print as raw text on the site, usually because the plugin that provided them was removed.
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.