Shortcode function returning outside of div PHP

I’ve created a shortcode for a custom menu in WordPress.

The problem is that my $menu is showing up above and outside of the side-nav and side-nav-menu divs.

Read More

I’ve tried just echoing/returning it without storing it in $var and I get the same issue.

Am I missing something?

function custom_menu() {
   $menu = wp_nav_menu( array( 'theme_location' => 'product-menu' ) );
   $var = '<div class="side-nav">
   <div class="side-nav-menu product-    nav">
   <p>Products</p>' . $menu . '
   </div></div>';
      return $var;
 }
 add_shortcode("custom", "custom_menu");

Related posts

2 comments

  1. wp_nav_menu() echos its output to screen, and this is what is causing your issue in your shortcode. As you know, echoing anything inside a shortcode have unexpected output. wp_nav_menu() has a parameter called echo which is set to true bu default. You can just add

    'echo' => false, 
    

    to your array of wp_nav_menu arguments and that should solve your issue

  2. Ok, the wp_nav_menu() echoes by default, so to store it in a variable you can do like you’d do with the regular widgets – output buffering:

    function custom_menu() {
        ob_start();
        wp_nav_menu( array( 'theme_location' => 'product-menu' ) );
        $menu = ob_get_contents();
        ob_end_clean();
    
        $var = '<div class="side-nav">
       <div class="side-nav-menu product-    nav">
       <p>Products</p>' . $menu . '
       </div></div>';
          return $var;
    
     }
     add_shortcode("custom", "custom_menu");
    

    This should work.

    What you are doing is start the output buffer with ob_start();, then everything you echo inside is caught in the buffer, then you output the contents of the buffer in the $menu variable, and clean the buffer. Then you can safely use the $menu variable as you wish

Comments are closed.