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");
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 calledecho
which is set to true bu default. You can just addto your array of
wp_nav_menu
arguments and that should solve your issueOk, 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: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