Jack Averill
Jack Averill

Reputation: 841

Custom shortcode always displays at top of page

I realise there are similar questions to this on here, but all contain slightly different code to mine. I have a custom shortcode configured in the functions.php file, and for some reason it always displays at the top of the page. Nothing I do seems to be able to move it. Is this a result of something in the code?

function menu_shortcode( $atts ) {
     return wp_nav_menu( array( 'theme_location' => 'header' ) );
}
add_shortcode( 'nav', 'menu_shortcode' );

Upvotes: 0

Views: 596

Answers (2)

Nathan Dawson
Nathan Dawson

Reputation: 19308

Your shortcode is returning wp_nav_menu() but that function will output by default. Shortcodes aren't allowed to generate output so you need to set echo to false to prevent it.

function menu_shortcode( $atts ) {
     return wp_nav_menu( array( 
         'theme_location' => 'header',
         'echo' => false, 
     ) );
}
add_shortcode( 'nav', 'menu_shortcode' );

Documentation:

The answer you received to your original question has been updated to fix the problem you've described: How to make a PHP function into a short code

Upvotes: 1

berend
berend

Reputation: 553

All right, I've tested it on my own WordPress install with the following code:

function menu_shortcode() {
     return wp_nav_menu( array( 'theme_location' => 'header' ) );
}
add_shortcode( 'b3_add_menu', 'menu_shortcode' );

I created a page called test and added the shortcode [b3_add_menu] to it. This is the result:

Test

For me the menu is not displayed only at the top of the page, could you maybe tell me where you placed your "nav" shortcode?

Upvotes: 1

Related Questions