Find Posts Using a Shortcode (WP-CLI)
Adds a "wp find-shortcode" command that lists every post, page or custom post that contains a given shortcode, with its status and edit link. Handy before removing a plugin.
Opens WPIDE on
Code
if ( ! defined( 'WP_CLI' ) || ! WP_CLI ) {
return;
}
WP_CLI::add_command( 'find-shortcode', function ( $args, $assoc_args ) {
global $wpdb;
$tag = sanitize_key( $args[0] );
$post_types = isset( $assoc_args['post_type'] ) ? array_map( 'sanitize_key', explode( ',', $assoc_args['post_type'] ) ) : get_post_types( array( 'public' => true ) );
$types_in = implode( ',', array_fill( 0, count( $post_types ), '%s' ) );
// Cheap LIKE filter first, then confirm with has_shortcode().
$rows = $wpdb->get_results( $wpdb->prepare(
"SELECT ID, post_title, post_type, post_status, post_content FROM {$wpdb->posts}
WHERE post_type IN ($types_in) AND post_status NOT IN ('trash','auto-draft','inherit') AND post_content LIKE %s
ORDER BY ID",
array_merge( $post_types, array( '%[' . $wpdb->esc_like( $tag ) . '%' ) )
) );
$items = array();
foreach ( $rows as $row ) {
if ( ! has_shortcode( $row->post_content, $tag ) && false === strpos( $row->post_content, '[' . $tag . ' ' ) && false === strpos( $row->post_content, '[' . $tag . ']' ) ) {
continue;
}
$items[] = array(
'ID' => $row->ID,
'type' => $row->post_type,
'status' => $row->post_status,
'title' => $row->post_title,
'edit' => admin_url( 'post.php?post=' . $row->ID . '&action=edit' ),
);
}
if ( ! $items ) {
WP_CLI::success( sprintf( 'No content uses [%s].', $tag ) );
return;
}
WP_CLI\Utils\format_items( $assoc_args['format'] ?? 'table', $items, array( 'ID', 'type', 'status', 'title', 'edit' ) );
}, array(
'shortdesc' => 'Lists content that contains a shortcode.',
'synopsis' => array(
array( 'type' => 'positional', 'name' => 'tag', 'description' => 'Shortcode tag, without brackets.' ),
array( 'type' => 'assoc', 'name' => 'post_type', 'optional' => true, 'description' => 'Comma-separated post types. Default: all public types.' ),
array( 'type' => 'assoc', 'name' => 'format', 'optional' => true, 'default' => 'table', 'options' => array( 'table', 'csv', 'json', 'count' ) ),
),
) );
Notes
Run it as "wp find-shortcode gallery --post_type=post,page --format=csv"; drafts and private posts are included.
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.