Merge menu blocks on mobile

// 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;
}

¿Te ha gustado?

Tengo una newsletter que alguna vez retomaré y seguramente sea pronto, así que te animo a que te suscribas para enviarte más cositas monas y desafiantes.

Formulario de suscripción

Al darte de alta en mi boletín, me comprometo a:

 1  Hablar de lo que me preocupa en la actualidad cultural y de las cosas con las que estoy disfrutando en ese momento con la intención de que te rumie la cabeza y podamos tener una conversación cultural activa.
 2  Contestarte si me escribes comentando algún tema del tratado en el correo correspondiente.
 3  Poner colorinchis y gifs monis.
 4  No mirar si te das de baja. Esta es una lista que no juzga, simplemente es disfrutona. Tampoco tiene métricas, los correos se envían a través de un servicio de envío de emails de sendgrid pero el sistema de envío es por medio de un plugin que he creado yo en WordPress. No hay proveedores de terceros que me digan «qué correo funciona más». Directamente paso del capitalismo.
 5  De vez en cuando te enviaré cosillas en las que participo u organizo. La mayoría son en Alicante y gratuitas, aunque si hay algo de pago, como un libro o curso o lo que sea, ¡será previamente avisado!

Nombre
Email *

Estos datos los gestiono yo misma, Flavia Bernárdez Rodríguez y están alojados en el servidor de Nicalia (una empresa de hosting sostenible buenísima cuyo datacenter está en España). Usaré los datos para enviarte emails sobre las cosas que hago, organizo o pienso. Te podrás dar de baja cuando quieras, bien cuando te envíe un mail, o bien diciéndomelo por cualquier método de contacto.

Habrás recibido un correo para confirmar tu suscripción

Tuvimos un error, por favor revisa y prueba de nuevo