2

I am using the wordpress walker class to append a template part after a menu li, however it is injecting the template parts above the entire menu structure. Here is what I've got

class bt_menu_walker extends Walker_Nav_Menu
{
    public function end_el(&$output, $item, $depth = 0, $args = array()) {
        $dir = get_template_directory() . '/partials';
        // Get file names from 'partials' directory
        $scan = scandir($dir);
        // Get css class names from menu elements
        $classes = empty( $item->classes ) ? array() : (array) $item->classes;
        foreach($scan as $file) {
            // Only grab files
            if (!is_dir("$file")) {
                // Just raw filenames
                $strip_extension = pathinfo($file, PATHINFO_FILENAME);
                // Match css class with filenames
                if ($classes[0] == $strip_extension) {
                    // Append template part after closing </li>
                    $output .= "</li>" . get_template_part( 'partials/' . $strip_extension );
                }
            }
        }
    }
}

As I've tested it, when I append other html to $output it displays directly after the closing </li> element as expected. Why does the get_template_part render above the menu structure?

Chris
  • 767
  • 4
  • 8
  • 22

1 Answers1

1

Because the template parts output echo's directly to the browser and the menu is in $output and will be later outputed. (that`s probably realy bad english)

Turn on output buffering to get the output of the template part:

if ($classes[0] == $strip_extension) {
    // Append template part after closing </li>
    $output .= "</li>";
    ob_start();
    get_template_part( 'partials/' . $strip_extension );
    $output .= ob_get_clean();
}

See ob_start() and ob_get_clean() for explanation.


By the way. A <ul> element should only contain <li> elements. Maybe this is not the best place for your extra output.

Andy Tschiersch
  • 3,716
  • 1
  • 17
  • 24