"Used In" Column for Synced Patterns
Adds a "Used in" column to the Patterns list (Appearance > Editor > Patterns > Manage) showing how many posts and pages include each synced pattern, so you know what changes will affect.
Opens WPIDE on
Code
add_filter( 'manage_wp_block_posts_columns', function ( $columns ) {
$columns['wpide_used_in'] = 'Used in';
return $columns;
} );
add_action( 'manage_wp_block_posts_custom_column', function ( $column, $pattern_id ) {
global $wpdb;
if ( 'wpide_used_in' !== $column ) {
return;
}
$counts = get_transient( 'wpide_synced_pattern_counts' );
if ( false === $counts ) {
$counts = array();
$rows = $wpdb->get_col(
"SELECT post_content FROM {$wpdb->posts} WHERE post_status IN ('publish','draft','private','future')
AND post_type NOT IN ('revision','wp_block') AND post_content LIKE '%<!-- wp:block %'"
);
foreach ( $rows as $content ) {
if ( preg_match_all( '/<!--\s+wp:block\s+\{[^}]*"ref":(\d+)/', $content, $matches ) ) {
foreach ( array_unique( $matches[1] ) as $ref ) {
$counts[ (int) $ref ] = ( $counts[ (int) $ref ] ?? 0 ) + 1;
}
}
}
set_transient( 'wpide_synced_pattern_counts', $counts, HOUR_IN_SECONDS );
}
$count = (int) ( $counts[ (int) $pattern_id ] ?? 0 );
echo $count ? esc_html( sprintf( _n( '%d item', '%d items', $count ), $count ) ) : '<span style="color:#787c82">not used</span>';
}, 10, 2 );
add_action( 'save_post', function ( $post_id, $post ) {
if ( 'revision' !== $post->post_type ) {
delete_transient( 'wpide_synced_pattern_counts' );
}
}, 10, 2 );
Notes
Counts are cached for an hour; patterns nested inside other patterns are counted once for the outer pattern only.
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.