diff --git a/src/wp-includes/media.php b/src/wp-includes/media.php
index afbdf332a2..5ab3cd1913 100644
--- a/src/wp-includes/media.php
+++ b/src/wp-includes/media.php
@@ -4780,9 +4780,12 @@ function get_post_galleries( $post, $html = true ) {
continue;
}
- // All blocks nested inside non-Gallery blocks should be in the root array.
- if ( $has_inner_blocks && 'core/gallery' !== $block['blockName'] ) {
- array_push( $post_blocks, ...$block['innerBlocks'] );
+ // Skip non-Gallery blocks.
+ if ( 'core/gallery' !== $block['blockName'] ) {
+ // Move inner blocks into the root array before skipping.
+ if ( $has_inner_blocks ) {
+ array_push( $post_blocks, ...$block['innerBlocks'] );
+ }
continue;
}
diff --git a/tests/phpunit/tests/media/getPostGalleries.php b/tests/phpunit/tests/media/getPostGalleries.php
index bd114b899f..d42dce5915 100644
--- a/tests/phpunit/tests/media/getPostGalleries.php
+++ b/tests/phpunit/tests/media/getPostGalleries.php
@@ -41,6 +41,82 @@ class Tests_Functions_getPostGalleries extends WP_UnitTestCase {
$this->assertEmpty( $galleries );
}
+ /**
+ * Test that only galleries are returned.
+ *
+ * @dataProvider data_returns_only_galleries
+ *
+ * @ticket 55203
+ *
+ * @param string $content The content of the post.
+ * @param string $needle The content of a non-gallery block.
+ */
+ public function test_returns_only_galleries( $content, $needle ) {
+ $image_id = $this->factory->attachment->create_object(
+ array(
+ 'file' => 'test.jpg',
+ 'post_parent' => 0,
+ 'post_mime_type' => 'image/jpeg',
+ 'post_type' => 'attachment',
+ )
+ );
+
+ $image_url = 'http://' . WP_TESTS_DOMAIN . '/wp-content/uploads/test.jpg';
+
+ $content = str_replace(
+ array( 'IMAGE_ID', 'IMAGE_URL' ),
+ array( $image_id, $image_url ),
+ $content
+ );
+
+ $post_id = $this->factory->post->create(
+ array(
+ 'post_content' => $content,
+ )
+ );
+
+ $galleries = get_post_galleries( $post_id );
+ $actual = implode( '', $galleries );
+
+ $this->assertStringNotContainsString( $needle, $actual );
+ }
+
+ /**
+ * Data provider.
+ *
+ * @return array
+ */
+ public function data_returns_only_galleries() {
+ $gallery = '
+
+
+
A paragraph before a gallery.
' . $gallery, + 'needle' => 'A paragraph before a gallery.', + ), + 'a paragraph after a gallery' => array( + 'content' => $gallery . 'A paragraph after a gallery.
', + 'needle' => 'A paragraph after a gallery.', + ), + ); + } + /** * Test that no srcs are returned for a shortcode gallery * in a post with no attached images.