| 1 |
<?php |
| 2 |
/** |
| 3 |
* Tabs Menu Block |
| 4 |
* |
| 5 |
* @package WordPress |
| 6 |
*/ |
| 7 |
|
| 8 |
/** |
| 9 |
* Render callback for core/tabs-menu. |
| 10 |
* |
| 11 |
* @since 7.0.0 |
| 12 |
* |
| 13 |
* @param array $attributes Block attributes. |
| 14 |
* @param string $content Block content (contains the tabs-menu-item template). |
| 15 |
* @param \WP_Block $block WP_Block instance. |
| 16 |
* |
| 17 |
* @return string Updated HTML. |
| 18 |
*/ |
| 19 |
function gutenberg_block_core_tabs_menu_render_callback( array $attributes, string $content, \WP_Block $block ): string { |
| 20 |
$tabs_list = $block->context['core/tabs-list'] ?? array(); |
| 21 |
|
| 22 |
if ( empty( $tabs_list ) ) { |
| 23 |
return ''; |
| 24 |
} |
| 25 |
|
| 26 |
// Get the first inner block as template (tabs-menu-item) |
| 27 |
$inner_blocks = $block->parsed_block['innerBlocks'] ?? array(); |
| 28 |
if ( empty( $inner_blocks ) ) { |
| 29 |
return ''; |
| 30 |
} |
| 31 |
$template_block = $inner_blocks[0]; |
| 32 |
|
| 33 |
// Build rendered tab items |
| 34 |
$tabs_markup = ''; |
| 35 |
foreach ( $tabs_list as $index => $tab ) { |
| 36 |
// Create context for this specific tab |
| 37 |
$tab_context = array_merge( |
| 38 |
$block->context, |
| 39 |
array( |
| 40 |
'core/tabs-menu-item-index' => $index, |
| 41 |
'core/tabs-menu-item-id' => $tab['id'] ?? '', |
| 42 |
'core/tabs-menu-item-label' => $tab['label'] ?? '', |
| 43 |
) |
| 44 |
); |
| 45 |
|
| 46 |
// Create new WP_Block instance with template and context |
| 47 |
$tab_block = new WP_Block( $template_block, $tab_context ); |
| 48 |
|
| 49 |
// Render the block |
| 50 |
$tabs_markup .= $tab_block->render(); |
| 51 |
} |
| 52 |
|
| 53 |
// Find the template block and replace it in $content with $tabs_markup |
| 54 |
$content = preg_replace( |
| 55 |
'/<button\b[^>]*\bwp-block-tabs-menu-item__template\b[^>]*>.*?<\/button>/si', |
| 56 |
$tabs_markup, |
| 57 |
$content |
| 58 |
); |
| 59 |
|
| 60 |
return $content; |
| 61 |
} |
| 62 |
|
| 63 |
/** |
| 64 |
* Registers the `core/tabs-menu` block on the server. |
| 65 |
* |
| 66 |
* @since 7.0.0 |
| 67 |
*/ |
| 68 |
function gutenberg_register_block_core_tabs_menu() { |
| 69 |
register_block_type_from_metadata( |
| 70 |
__DIR__ . '/tabs-menu', |
| 71 |
array( |
| 72 |
'render_callback' => 'gutenberg_block_core_tabs_menu_render_callback', |
| 73 |
) |
| 74 |
); |
| 75 |
} |
| 76 |
add_action( 'init', 'gutenberg_register_block_core_tabs_menu', 20 ); |
| 77 |
|