Welcome to the Treehouse Community

Want to collaborate on code errors? Have bugs you need feedback on? Looking for an extra set of eyes on your latest project? Get support with fellow developers, designers, and programmers of all backgrounds and skill levels here with the Treehouse Community! While you're at it, check out some resources Treehouse students have shared here.

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and join thousands of Treehouse students and alumni in the community today.

Start your free trial

WordPress

Gabriel Ward
Gabriel Ward
20,222 Points

Adding wp_nav_menu in jQuery

I'm building a Wordpress theme, and I'm showing my wp_nav_menu on an overlay. I understand it's best practice to append an overlay via jQuery, and not have it directly in the html. So this is what I have in my app.js

var $overlay = $('<div class="overlay">
                                  <?php 
                                          $defaults = array(
                                              "container" => false,
                                              "theme_location" => "primary-menu",
                                              "menu_class" => "main-nav group");wp_nav_menu( $defaults ); 
                                    ?>
                        </div>');

This all works fine if I have this code directly in my header.php, but I'm trying to append this in jQuery. The overlay shows fine, but the php code just shows up as text on the overlay, the menu doesn't display. I'm not sure how to make the php code work in the app.js.

Any advice would be greatly appreciated.

1 Answer

Casey Ydenberg
Casey Ydenberg
15,622 Points

There's no way to do exactly that. The PHP parser never sees JS files.

As a possible alternative, you could attempt to pass the HTML string to a JavaScript variable by using wp_localize_script. Usually I put this somewhere in my functions.php right after enqueuing the main script.

Casey Ydenberg
Casey Ydenberg
15,622 Points

One note of caution: I'm not sure exactly what you mean by overlay, but I disagree that it's best practice to place a nav menu in JavaScript. For one thing, some users might have difficultly navigating your site (ie - they have JS disabled or if their connection is spotty and doesn't get the file). Not to mention it'll make it harder/impossible for Google to find all of your content.

Not trying to open up the progressive enhancement can of worms, just my opinion.

Gabriel Ward
Gabriel Ward
20,222 Points

Hi Casey,

Thanks for your reply.

According to the overlay tutorial in the jQuery basics course on treehouse, it's best practice to place the overlay in jQuery and not directly in the html. So in keeping with this, I was assuming that it would be good to place the menu in the overlay, within jQuery. Perhaps Andrew Chalkley and Zac Gordon might have an opinion on this...?