Shortcode Function Returning Outside of PHP Div

I have created a shortcode for a custom menu in Wordpress.

The problem is that my $ menu is displayed at the top and outside of the div-side-nav and side-nav-menu.

I tried just echoing / returning it without saving it in $ var and I am getting the same problem.

Did I miss 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"); 
+4
source share
2 answers

wp_nav_menu() echos displays it and that is what causes the problem in your short code. As you know, repeating something inside a shortcode has an unexpected exit. wp_nav_menu() has a parameter named echo that is set to true bu by default. You can just add

 'echo' => false, 

to your array of arguments wp_nav_menu , and this should solve your problem.

+5
source

Ok, the wp_nav_menu() echo is by default, therefore, to save it in a variable, you can do the same as with ordinary 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"); 

That should work.

What you do is run the output buffer using ob_start(); , then everything that you echo inside gets into the buffer, then you display the contents of the buffer in the $menu variable and clear the buffer. Then you can safely use the $menu variable as you wish

+1
source

All Articles