WordPress Admin Bar

Hackneyed Hero

Working with the WordPress Admin Bar on a Site with a Sticky Navigation Bar

When using a menu/topbar with jQuery to fix the element when it hits the top of the window, it will conflict with the WordPress admin bar for logged-in users. A top margin on the menu will fix this, but first we need to know if the user is logged in or not.

In the element tag, have WP check to see if the admin bar (Toolbar) is present and check the user status then add a class for logged-in users.

Example:
<nav class="nav <?php if ( is_user_logged_in() && is_admin_bar_showing() ) { echo 'logged-in'; } ?>" id="nav" role="navigation">
This will add the class "logged-in" to the nav tag. Use CSS to add a top margin to the menu element so that it will clear the admin bar above it.

The height of the desktop admin bar is 32px. It changes to 46px high for tablets and phones at the 782px break point. At 600px the admin bar changes from fixed to absolute position, which means it will scroll, so we won't need a margin. (Yes, I realize that was not mobile-first language.)

Apply the coresponding margins to the menu when it has both the sticky class and the logged-in class. I used a transition on the nav tag to have it slide gently into place on scroll, but I put it on the logged-in class so that it will snap back into place when scrolling back up.


Lorem ipsum dolor sit amet, consectetur adipiscing elit. Donec quis sapien quis mauris aliquam semper sed in libero. Curabitur sagittis magna erat, et porttitor libero mollis at. Mauris venenatis consequat feugiat. Nulla vestibulum felis ut felis fringilla, ac accumsan mauris suscipit. Aliquam malesuada massa ac varius lacinia. In semper metus nisi, ac viverra arcu facilisis eget! Interdum et malesuada fames ac ante ipsum primis in faucibus.

Praesent volutpat lectus at magna gravida semper. Nam consectetur elementum tortor, nec suscipit augue dignissim eget. Nulla in dictum augue. Quisque rutrum varius lorem vitae vehicula. Suspendisse mattis congue nisi vitae lobortis. Interdum et malesuada fames ac ante ipsum primis in faucibus. Ut in venenatis ipsum, quis congue tellus. Fusce laoreet magna tortor, ut pharetra diam posuere ac. Curabitur porttitor fringilla egestas. Donec tincidunt urna vel nulla convallis laoreet. Nulla molestie neque odio, at sodales nibh lobortis vitae.