I'm adding extra menu items by using WP's filter wp_nav_menu_items but the menus fall outside the ul class.

My code is as follows:

     function your_custom_menu_item ( $items, $args ) {

    global $mytheme_option; 

    $layout = $kiwi_theme_option['home-blocks-logged']['enabled'];

    if ($args->theme_location == 'vendor_navigation') {

        if ($layout && $args->theme_location == 'top_navigation'): foreach ($layout as $key=>$value) {               
            switch($key) {   
                case 'cart': 
                    $items_icon = get_template_part( 'templates/topbar', 'rolecart' ); 

                case 'dashboard': 
                    $items_icon = get_template_part( 'templates/topbar', 'roledashboard' );


    return $items_icon . $items;    

add_filter( 'wp_nav_menu_items', 'your_custom_menu_item', 10, 2 );

However, it will look like this in the source code: Image - Source Code

I'm using Redux framework field sorter:

Stackoverflow :: Redux sorter - retrieve dynamic pages

Redux sorter field

Can anyone tell me what I'm doing wrong?


The problem are these lines:

$items_icon = get_template_part( 'templates/topbar', 'rolecart' ); 
$items_icon = get_template_part( 'templates/topbar', 'roledashboard' );

where you expect get_template_part() to return the output, but it doesn't, because it's basically a wrapper for require() and require_once() calls.

This means the template parts are not part of the returned filter value.

I agree that the get_ prefix is confusing here!

It would make more sense to have it the_template_part() instead ;-)

Here's some hacking with output buffering. Let's use the wpse_return_ prefix it emphasize that it returns the output:

if( ! function_exists( 'wpse_return_template_part' ) )
    function wpse_return_template_part( $first = '', $second = '' )
        get_template_part( $first, $second );
        return ob_get_clean();

and then

if( function_exists( 'wpse_return_template_part' ) )
    $items_icon = wpse_return_template_part( 'templates/topbar', 'rolecart' ); 
  • What should I use instead of get_template_part then? – kiarashi Dec 10 '15 at 14:18
  • move the parts into the filter callback as variables or hack with output buffering are two workarounds @kiarashi – birgire Dec 10 '15 at 14:28
  • I almost got it working... Please see my answer below. – kiarashi Dec 10 '15 at 15:01
  • It should be sufficient to only check once for the function's existence, Wrap your code inside the filter callback with it, but leave the return out of it @kiarashi – birgire Dec 10 '15 at 15:19
  • Yes, I just figured it out. You were quicker with your answer. – kiarashi Dec 10 '15 at 15:20

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.