Emma Harris
Emma Harris

Reputation: 65

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.

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");

Upvotes: 4

Views: 1071

Answers (2)

dingo_d
dingo_d

Reputation: 11670

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

Upvotes: 1

Pieter Goosen
Pieter Goosen

Reputation: 9941

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

Upvotes: 5

Related Questions