| 1 |
<?php |
| 2 |
/** |
| 3 |
* Tab List Block |
| 4 |
* |
| 5 |
* @package WordPress |
| 6 |
*/ |
| 7 |
|
| 8 |
/** |
| 9 |
* Render callback for core/tab-list. |
| 10 |
* |
| 11 |
* Re-renders each tab inner block with per-item context (index, id, |
| 12 |
* label) injected from the tabs-list, so the tab render callback |
| 13 |
* can add the correct IAPI directives for each button. |
| 14 |
* |
| 15 |
* @since 7.0.0 |
| 16 |
* |
| 17 |
* @param array $attributes Block attributes. |
| 18 |
* @param string $content Block content (rendered inner blocks from save.js). |
| 19 |
* @param \WP_Block $block WP_Block instance. |
| 20 |
* |
| 21 |
* @return string Updated HTML. |
| 22 |
*/ |
| 23 |
function gutenberg_block_core_tab_list_render_callback( array $attributes, string $content, \WP_Block $block ): string { |
| 24 |
$tabs_list = $block->context['core/tabs-list'] ?? array(); |
| 25 |
|
| 26 |
if ( empty( $tabs_list ) ) { |
| 27 |
return $content; |
| 28 |
} |
| 29 |
|
| 30 |
// Re-render each tab with per-item context (index, id, label). |
| 31 |
// Match by position so items align with their corresponding tabs. |
| 32 |
$buttons_html = ''; |
| 33 |
$tab_position = 0; |
| 34 |
|
| 35 |
foreach ( $block->parsed_block['innerBlocks'] ?? array() as $parsed_tab ) { |
| 36 |
if ( 'core/tab' !== ( $parsed_tab['blockName'] ?? '' ) ) { |
| 37 |
continue; |
| 38 |
} |
| 39 |
|
| 40 |
$tab = $tabs_list[ $tab_position ] ?? null; |
| 41 |
$tab_index = $tab_position; |
| 42 |
++$tab_position; |
| 43 |
|
| 44 |
// Skip tabs with no matching tab panel. |
| 45 |
if ( null === $tab ) { |
| 46 |
continue; |
| 47 |
} |
| 48 |
|
| 49 |
$item_context = array_merge( |
| 50 |
$block->context, |
| 51 |
array( |
| 52 |
'core/tab-index' => $tab_index, |
| 53 |
'core/tab-id' => $tab['id'] ?? '', |
| 54 |
'core/tab-label' => $tab['label'] ?? '', |
| 55 |
) |
| 56 |
); |
| 57 |
|
| 58 |
$tab_block = new WP_Block( $parsed_tab, $item_context ); |
| 59 |
$buttons_html .= $tab_block->render(); |
| 60 |
} |
| 61 |
|
| 62 |
// Rebuild the wrapper using get_block_wrapper_attributes(). |
| 63 |
$wrapper_attributes = get_block_wrapper_attributes( array( 'role' => 'tablist' ) ); |
| 64 |
return sprintf( '<div %s>%s</div>', $wrapper_attributes, $buttons_html ); |
| 65 |
} |
| 66 |
|
| 67 |
/** |
| 68 |
* Registers the `core/tab-list` block on the server. |
| 69 |
* |
| 70 |
* @since 7.0.0 |
| 71 |
*/ |
| 72 |
function gutenberg_register_block_core_tab_list() { |
| 73 |
register_block_type_from_metadata( |
| 74 |
__DIR__ . '/tab-list', |
| 75 |
array( |
| 76 |
'render_callback' => 'gutenberg_block_core_tab_list_render_callback', |
| 77 |
) |
| 78 |
); |
| 79 |
} |
| 80 |
add_action( 'init', 'gutenberg_register_block_core_tab_list', 20 ); |
| 81 |
|