Created
July 18, 2022 20:23
-
-
Save kimcoleman/9cd6948bf5aa8febe8d9cbcd36615230 to your computer and use it in GitHub Desktop.
Add a column to the Reusable Blocks screen to show the posts the block is used in.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?php | |
/** | |
* Add column to show all posts a reusable block is used in. | |
*/ | |
function my_reusable_blocks_screen_add_column( $columns ) { | |
$columns['posts_used_in'] = esc_html__( 'Used In', 'textdomain' ); | |
return $columns; | |
} | |
add_filter( 'manage_wp_block_posts_columns', 'my_reusable_blocks_screen_add_column' ); | |
/** | |
* Populate the 'posts_used_in' column of the Reusable Blocks screen. | |
* | |
* This code is adapted from https://wordpress.org/plugins/reusable-blocks-extended/ | |
*/ | |
function my_reusable_blocks_screen_populate_column( $column, $ID ) { | |
global $post; | |
switch( $column ) { | |
case 'posts_used_in' : | |
global $wpdb; | |
$tag = '<!-- wp:block {"ref":' . $ID . '}'; | |
$search = '%' . $wpdb->esc_like($tag) . '%'; | |
$instances = $wpdb->get_results( "SELECT * FROM {$wpdb->prefix}posts WHERE post_content LIKE '$search' and post_type NOT IN ('revision', 'attachment', 'nav_menu_item')" ); | |
if ( ! empty( $instances ) ) { | |
$post_links = array(); | |
foreach ( $instances as $instance ) { | |
$post_links[] = '<a href="' . get_edit_post_link( $instance->ID ) . '">' . $instance->post_title . '</a>'; | |
} | |
echo implode( ', ', $post_links ); | |
} else { | |
esc_html_e( '—', 'textdomain' ); | |
} | |
break; | |
default : | |
break; | |
} | |
} | |
add_action( 'manage_wp_block_posts_custom_column' , 'my_reusable_blocks_screen_populate_column', 10, 2 ); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment