// Add variations to the navigation block
add_filter( 'get_block_type_variations', 'register_navigation_block_variations', 10, 2 );
function register_navigation_block_variations( $variations, $block_type ) {
if ( 'core/navigation' !== $block_type->name ) {
return $variations;
}
$variations[] = array(
'name' => 'header-menu-left',
'title' => __( 'Left Header Menu', 'your-theme' ),
'description' => __( 'Navigation menu for the left side of the header', 'your-theme' ),
'icon' => 'navigation',
'attributes' => array(
'className' => 'is-header-menu-left',
),
);
$variations[] = array(
'name' => 'header-menu-right',
'title' => __( 'Right Header Menu', 'your-theme' ),
'description' => __( 'Navigation menu for the right side of the header', 'your-theme' ),
'icon' => 'navigation',
'attributes' => array(
'className' => 'is-header-menu-right',
),
);
return $variations;
}
// Merge header navigation blocks
add_filter( 'render_block_core/navigation', 'merge_header_navigation_blocks', 10, 2 );
function merge_header_navigation_blocks( $block_content, $block ) {
if ( is_admin() || wp_is_json_request() ) {
return $block_content;
}
static $left_menu_items = '';
static $is_merged = false;
// Check if this is one of our header menus
$className = isset($block['attrs']['className']) ? $block['attrs']['className'] : '';
$is_left_menu = strpos($className, 'is-header-menu-left') !== false;
$is_right_menu = strpos($className, 'is-header-menu-right') !== false;
if ( !$is_left_menu && !$is_right_menu ) {
return $block_content;
}
if ( wp_is_mobile() ) {
if ( $is_left_menu ) {
// Extract the ul content from the left menu
if (preg_match('/<ul\s+class="[^"]*wp-block-navigation__container[^"]*"[^>]*>(.*?)<\/ul>/s', $block_content, $matches)) {
$left_menu_items = $matches[1];
}
return '';
}
if ( $is_right_menu && !empty($left_menu_items) && !$is_merged ) {
$is_merged = true;
// Insert left menu items at the start of the right menu's ul
return preg_replace(
'/(<ul\s+class="[^"]*wp-block-navigation__container[^"]*"[^>]*>)(.*?)(<\/ul>)/s',
'$1' . $left_menu_items . '$2$3',
$block_content,
1
);
}
}
return $block_content;
}