Skip to content

Commit

Permalink
Change order of attribs and check for innerBlocks
Browse files Browse the repository at this point in the history
  • Loading branch information
Glen Davies authored and ramonjd committed Nov 3, 2021
1 parent d26a848 commit 5ac2a85
Showing 1 changed file with 5 additions and 5 deletions.
10 changes: 5 additions & 5 deletions packages/block-library/src/image/index.php
Original file line number Diff line number Diff line change
Expand Up @@ -8,8 +8,8 @@
/**
* Adds a data-id attribute to the core Image block when nested in a Gallery block.
*
* @param WP_Post $post The block attributes.
* @return string Returns the block content with the data-id attribute added.
* @param WP_Post $post The WP post.
* @return string Returns the post content with the data-id attribute added to gallery images.
*/
function get_block_core_image_post_content( $post ) {
if ( is_admin() ) {
Expand All @@ -19,14 +19,14 @@ function get_block_core_image_post_content( $post ) {
$content = $post->post_content;
$blocks = parse_blocks( $content );
foreach ( $blocks as $block ) {
if ( 'core/gallery' === $block['blockName'] ) {
if ( 'core/gallery' === $block['blockName'] && ! empty( $block['innerBlocks'] ) ) {
foreach ( $block['innerBlocks'] as $inner_block ) {
if ( 'core/image' === $inner_block['blockName'] ) {
if ( isset( $inner_block['attrs']['id'] ) ) {
$image_id = esc_attr( $inner_block['attrs']['id'] );
$data_id_attribute = 'data-id="' . $image_id . '"';
$class_string = 'class="wp-image-' . $image_id . '"';
$content = str_replace( $class_string, $class_string . ' ' . $data_id_attribute, $content );
$content = str_replace( $class_string, $data_id_attribute . ' ' . $class_string, $content );
}
}
}
Expand All @@ -36,4 +36,4 @@ function get_block_core_image_post_content( $post ) {
$post->post_content = $content;
}

add_action( 'the_post', 'get_block_core_image_post_content', 10, 2 );
add_action( 'the_post', 'get_block_core_image_post_content', 10, 1 );

0 comments on commit 5ac2a85

Please sign in to comment.