How to prevent Widget from echoing to wrong position in DOM

I am following this tutorial to create a mega menu in WordPress. It utilizes widgets to house the submenu content. My issue is when echoing the widget, it renders outside of its parent in the DOM.

Here’s my current code:

<ul class="menu">
    <?php
        $locations = get_nav_menu_locations();
        if ( isset( $locations[ 'mega_menu' ] ) ) {
            $menu = get_term( $locations[ 'mega_menu' ], 'nav_menu' );
            if ( $items = wp_get_nav_menu_items( $menu->name ) ) {
                foreach ( $items as $item ) {
                    echo "<li>";
                    echo "<a href="{$item->url}">{$item->title}</a>";
                    if ( is_active_sidebar( 'mega-menu-widget-area-' . $item->ID ) ) {
                        echo "<div id="mega-menu-{$item->ID}" class="mega-menu">";
                            dynamic_sidebar( 'mega-menu-widget-area-' . $item->ID );
                        echo "</div>";
                    }
                echo "</li>";
                }
            }
        }
    ?>
</ul>

The widget content is not rendering as a child of the

, but rather it is rendering as a sibling to its parent

  • .

    Current DOM output:

    <ul class="menu">
      <li>
        <a href="http://water-wp/">Home</a>
      </li>
      <li>
        <a href="http://water-wp/solutions/">Solutions</a>
      </li>
    
      <!-- Should not be a list item, but rather a child div of the previous list item -->
      <li id="text-2" class="widget widget_text">
        <h2 class="widgettitle">Heading</h2>
            <div class="textwidget">hnjsf skhdfj sdf</div>
      </li>
      <div id="mega-menu-32" class="mega-menu"> 1</div>      
    </ul>
    

    Desired DOM output:

    <ul class="menu">
      <li>
        <a href="http://water-wp/">Home</a>
      </li>
      <li>
        <a href="http://water-wp/solutions/">Solutions</a>
    
        <div id="mega-menu-32" class="mega-menu">
          <h2 class="widgettitle">Heading</h2>
          <div class="textwidget">hnjsf skhdfj sdf</div>
        </div>       
      </li>
    </ul>
    

    Read more here: How to prevent Widget from echoing to wrong position in DOM

  • Leave a Reply

    Your email address will not be published. Required fields are marked *