Create mega menu using GB on GP sites

Updated on:

Mega menu is a powerful menu layout, however, it usually requires a specific mega menu plugin or lots of CSS customization. In this article, we will introduce a method to create a mega menu using GenerateBlocks and break it down into easy steps. Lots of thanks to David who initially created the PHP function.


1. Create the parent mega menu item

1.1 Go to appearance > menus, add a custom link to the menu. Although it’s going to be a parent menu item, do NOT add child menu items to it. The child menu items will be created using GenerateBlocks in a GP element.

1.2 Add both CSS classes gp_mega_item and menu-item-has-children to the parent menu item that will host the GB mega menu.

1.3 Set the Title attribute, it will be part of the custom hook name.

Note: if you don’t see the CSS Classes or the Title attribute option, click the Screen Options tab on the top right corner, and tick both the CSS Classes and Title Attribute boxes.

2. Create a hook for the sub menu items

The PHP code below creates a hook for the sub-menu items.

add_filter( 'walker_nav_menu_start_el', 'yh_sub_menu_item_hook', 10, 4 );

function yh_sub_menu_item_hook( $item_output, $item, $depth, $args ) {

    // Specify menu item class to target
    $class_string = 'gp_mega_item';
    $menu_item_classes = $item->classes;
    if ( empty( $menu_item_classes ) || !in_array( $class_string , $menu_item_classes ) ) {
        return $item_output;
	 $menu_item_title  = $item->attr_title; 
    // create custom hook from $class_string and $menu_item_title
    // example result gp_mega_menu_{menu-item-name}
    $custom_hook_name = $class_string . '_' . $menu_item_title;
    // Add our common and specific hooks
    <ul class="sub-menu custom-sub-menu">
        <?php do_action('gp_before_mega_item'); ?>
	<?php do_action($custom_hook_name); ?>
	<?php do_action('gp_after_mega_item'); ?>
    $custom_sub_menu_html = ob_get_clean();
    // return the output after the menu items anchor
    $item_output .= $custom_sub_menu_html;

    return $item_output;

3. Create the mega sub menu items layout using GB in GP’s element

3-1. Add a Block element – hook, and create the mega menu layout you want using GB blocks.

3-2. Set the Element type to Hook, Hook name to gp_mega_item_*. The * matches the parent menu item’s title attribute set in step 1.3. In my example, the hook name would be gp_mega_item_services.

You are All set! check the final result on the front end

Note: This method is used to create an intricate layout for a submenu. However, it might lack certain structures typically found in a menu.