wpseek.com
A WordPress-centric search engine for devs and theme authors
block_core_gallery_render › WordPress Function
Since6.0.0
Deprecatedn/a
› block_core_gallery_render ( $attributes, $content, $block )
| Parameters: (3) |
|
| Returns: |
|
| Defined at: |
|
| Codex: |
Renders the `core/gallery` block on the server.
Source
function block_core_gallery_render( $attributes, $content, $block ) {
static $global_styles = null;
// In dynamic mode the gallery's images are resolved at render time instead of
// being authored as inner blocks, so `save.js` persists at most the
// gallery-level caption — a bare `<figcaption>`, or nothing when there is no
// caption. Resolve the configured source to a list of attachments, render an
// image block for each, and build the gallery `<figure>` wrapper from scratch.
// The gap/randomOrder/lightbox post-processing below then runs over the
// constructed markup unchanged.
if ( ! empty( $attributes['dynamicContent'] ) ) {
$attachment_ids = block_core_gallery_resolve_dynamic_source( $attributes['dynamicContent'], $block );
// Nothing resolved — no attachments, or an unrecognized source. Render
// nothing rather than an empty gallery wrapper; a saved caption is
// meaningless without images, so it is intentionally dropped too.
if ( empty( $attachment_ids ) ) {
return '';
}
// The source query only fetched IDs (`fields => ids`), which skips
// WP_Query's cache priming. Each image rendered below reads the
// attachment post and its meta (via `wp_get_attachment_image()`,
// `get_post()`, etc.), so warm the post and meta caches in a single pair
// of queries up front instead of paying ~two queries per attachment.
// Term cache is left cold: the render path doesn't read attachment terms.
if ( count( $attachment_ids ) > 1 ) {
_prime_post_caches( $attachment_ids, false, true );
}
// Expose the gallery's provided context (plus galleryId/postId/postType)
// to each image block, since these images are rendered outside the
// gallery's real inner-block tree.
$image_context = array_merge(
is_array( $block->context ) ? $block->context : array(),
array(
'allowResize' => $attributes['allowResize'] ?? false,
'imageCrop' => $attributes['imageCrop'] ?? true,
'fixedHeight' => $attributes['fixedHeight'] ?? true,
'navigationButtonType' => $attributes['navigationButtonType'] ?? 'icon',
)
);
$images_markup = '';
foreach ( $attachment_ids as $attachment_id ) {
$images_markup .= block_core_gallery_render_dynamic_image( $attachment_id, $attributes, $image_context );
}
// Build the wrapper rather than parsing/splicing saved markup.
// `get_block_wrapper_attributes()` supplies the block-support
// classes/styles (align, color, border, spacing, anchor id); the layout
// render filter adds the flex layout classes downstream — the same way a
// static gallery's wrapper is composed (`useBlockProps.save()` plus that
// filter). Only the gallery-specific classes are added explicitly, and
// they mirror `save.js` (kept in sync deliberately — see that file).
$gallery_classes = 'wp-block-gallery has-nested-images';
$gallery_classes .= isset( $attributes['columns'] )
? ' columns-' . (int) $attributes['columns']
: ' columns-default';
if ( $attributes['imageCrop'] ?? true ) {
$gallery_classes .= ' is-cropped';
}
$wrapper_attributes = get_block_wrapper_attributes( array( 'class' => $gallery_classes ) );
// In dynamic mode `save.js` persists only the gallery-level caption, so
// `$content` is the saved `<figcaption>` (or empty). Append it after the
// resolved images — matching the static gallery's `{images}{caption}`
// order — without parsing it.
$content = sprintf( '<figure %s>%s%s</figure>', $wrapper_attributes, $images_markup, $content );
}
// Adds a style tag for the --wp--style--unstable-gallery-gap var.
// The Gallery block needs to recalculate Image block width based on
// the current gap setting in order to maintain the number of flex columns
// so a css var is added to allow this.
$style_attr = is_array( $attributes['style'] ?? null )
? $attributes['style']
: array();
if (
defined( 'IS_GUTENBERG_PLUGIN' ) &&
IS_GUTENBERG_PLUGIN &&
function_exists( 'gutenberg_resolve_style_state_aliases' )
) {
$style_attr = gutenberg_resolve_style_state_aliases( $style_attr, 'core/gallery' );
}
$unique_gallery_classname = wp_unique_id( 'wp-block-gallery-' );
$processed_content = new WP_HTML_Tag_Processor( $content );
$processed_content->next_tag();
$processed_content->add_class( $unique_gallery_classname );
// --gallery-block--gutter-size is deprecated. --wp--style--gallery-gap-default should be used by themes that want to set a default
// gap on the gallery.
$fallback_gap = 'var( --wp--style--gallery-gap-default, var( --gallery-block--gutter-size, var( --wp--style--block-gap, 0.5em ) ) )';
if ( null === $global_styles ) {
$global_styles = function_exists( 'wp_get_global_styles' ) ? wp_get_global_styles() : array();
}
$global_gallery_styles = $global_styles['blocks']['core/gallery'] ?? array();
$global_gallery_gap = $global_gallery_styles['spacing']['blockGap'] ?? $fallback_gap;
$has_block_gap = is_array( $style_attr['spacing'] ?? null ) && array_key_exists( 'blockGap', $style_attr['spacing'] );
// Prefer the block's own gap value, then Gallery global styles. Missing
// values fall back to the Gallery blockGap default.
$block_gap = $has_block_gap
? $style_attr['spacing']['blockGap']
: $global_gallery_gap;
$gap_column = block_core_gallery_get_column_gap_value( $block_gap, $fallback_gap );
// Set the CSS variable to the column value for Gallery's flex width calculations.
$gallery_styles = array(
array(
'selector' => ".wp-block-gallery.{$unique_gallery_classname}",
'declarations' => array(
'--wp--style--unstable-gallery-gap' => $gap_column,
),
),
);
$global_settings = wp_get_global_settings();
$viewport_settings = $global_settings['viewport'] ?? null;
$responsive_media_queries = array();
foreach ( array( 'WP_Theme_JSON_Gutenberg', 'WP_Theme_JSON' ) as $theme_json_class_name ) {
if ( method_exists( $theme_json_class_name, 'get_viewport_media_queries' ) ) {
$responsive_media_queries = $theme_json_class_name::get_viewport_media_queries( $viewport_settings );
break;
}
}
foreach ( $responsive_media_queries as $breakpoint => $media_query ) {
$viewport_style = $style_attr[ $breakpoint ] ?? null;
$has_viewport_block_gap = is_array( $viewport_style ) &&
is_array( $viewport_style['spacing'] ?? null ) &&
array_key_exists( 'blockGap', $viewport_style['spacing'] );
$has_global_viewport_block_gap = is_array( $global_gallery_styles[ $breakpoint ]['spacing'] ?? null ) &&
array_key_exists( 'blockGap', $global_gallery_styles[ $breakpoint ]['spacing'] );
// Viewport-specific block values win. Gallery global viewport values
// only apply when the block has no base gap, so they do not override an instance value.
if ( $has_viewport_block_gap ) {
$viewport_gap = $viewport_style['spacing']['blockGap'];
} elseif ( ! $has_block_gap && $has_global_viewport_block_gap ) {
$viewport_gap = $global_gallery_styles[ $breakpoint ]['spacing']['blockGap'];
} else {
continue;
}
if ( null === $viewport_gap ) {
continue;
}
$gallery_styles[] = array(
'selector' => ".wp-block-gallery.{$unique_gallery_classname}",
'declarations' => array(
'--wp--style--unstable-gallery-gap' => block_core_gallery_get_column_gap_value(
$viewport_gap,
$fallback_gap
),
),
'rules_group' => $media_query,
);
}
wp_style_engine_get_stylesheet_from_css_rules(
$gallery_styles,
array( 'context' => 'block-supports' )
);
// The WP_HTML_Tag_Processor class calls get_updated_html() internally
// when the instance is treated as a string, but here we explicitly
// convert it to a string.
$updated_content = $processed_content->get_updated_html();
/*
* Randomize the order of image blocks. Ideally we should shuffle
* the `$parsed_block['innerBlocks']` via the `render_block_data` hook.
* However, this hook doesn't apply inner block updates when blocks are
* nested.
* @todo In the future, if this hook supports updating innerBlocks in
* nested blocks, it should be refactored.
*
* @see: https://github.com/WordPress/gutenberg/pull/58733
*/
if ( ! empty( $attributes['randomOrder'] ) ) {
// This pattern matches figure elements with the `wp-block-image`
// class to avoid the gallery's wrapping `figure` element and
// extract images only.
$pattern = '/<figure[^>]*\bwp-block-image\b[^>]*>.*?<\/figure>/s';
preg_match_all( $pattern, $updated_content, $matches );
if ( $matches ) {
$image_blocks = $matches[0];
shuffle( $image_blocks );
$i = 0;
$updated_content = preg_replace_callback(
$pattern,
static function () use ( $image_blocks, &$i ) {
return $image_blocks[ $i++ ];
},
$updated_content
);
}
}
// Gets all image IDs from the state that match this gallery's ID.
$state = wp_interactivity_state( 'core/image' );
$gallery_id = $block->context['galleryId'] ?? null;
$image_ids = array();
// Extracts image IDs from state metadata that match the current gallery ID.
if ( isset( $gallery_id ) && isset( $state['metadata'] ) ) {
foreach ( $state['metadata'] as $image_id => $metadata ) {
if ( isset( $metadata['galleryId'] ) && $metadata['galleryId'] === $gallery_id ) {
$image_ids[] = $image_id;
}
}
}
// If there are image IDs associated with this gallery, set interactivity
// attributes and order metadata for lightbox navigation.
if ( ! empty( $image_ids ) ) {
$total = count( $image_ids );
$lightbox_index = 0;
$processor = new WP_HTML_Tag_Processor( $updated_content );
$processor->next_tag();
$processor->set_attribute( 'data-wp-interactive', 'core/gallery' );
$processor->set_attribute(
'data-wp-context',
wp_json_encode(
array( 'galleryId' => $gallery_id ),
JSON_HEX_TAG | JSON_HEX_APOS | JSON_HEX_QUOT | JSON_HEX_AMP
)
);
while ( $processor->next_tag( 'figure' ) ) {
$wp_key = $processor->get_attribute( 'data-wp-key' );
if ( $wp_key && isset( $state['metadata'][ $wp_key ] ) ) {
$alt = $state['metadata'][ $wp_key ]['alt'];
wp_interactivity_state(
'core/image',
array(
'metadata' => array(
$wp_key => array(
'customAriaLabel' => empty( $alt )
/* translators: %1$s: current image index, %2$s: total number of images */
? sprintf( __( 'Enlarged image %1$s of %2$s' ), $lightbox_index + 1, $total )
/* translators: %1$s: current image index, %2$s: total number of images, %3$s: Image alt text */
: sprintf( __( 'Enlarged image %1$s of %2$s: %3$s' ), $lightbox_index + 1, $total, $alt ),
/* translators: %1$s: current image index, %2$s: total number of images */
'triggerButtonAriaLabel' => sprintf( __( 'Enlarge %1$s of %2$s' ), $lightbox_index + 1, $total ),
'order' => $lightbox_index,
),
),
)
);
++$lightbox_index;
}
}
return $processor->get_updated_html();
}
return $updated_content;
}