Got another Quick Tip for you.
Did you notice the Twitter Button in my menu? I have a few custom buttons up by my logo, but the twitter button is special. It using the twitter API instead of just linking you to my Twitter profile.
The code for this is in a couple parts. The first part is a html file that handles everything. It is loaded in an iframe. That isn’t super important to this quick tip though. The important part is, well have you ever tried adding an iframe to the WordPress custom menu? You can’t.
So how do you get around this? There are tutorials on adding code to the end of a menu, but I want to put code in the middle of the menu. Turns out it is really easy to do.
add_filter( 'wp_nav_menu', 'ntg_twitter_follow_button' ); /** * Replaces the twitter menu link with twitter button iframe * * @author Nick the Geek * @param string $menu * @return string */ function ntg_twitter_follow_button( $menu ) { $url = htmlspecialchars( 'http://nickgeek.com/wp-content/themes/tapestry/twitter.html?button=null&text_color=null&link_color=null&preview=true&screen_name=Nick_theGeek&bg=light&show_count=false&lang=en' ); $menu = str_replace( '<a href="http://twitter.com/Nick_theGeek">Follow me on Twitter</a>', '<iframe scrolling="no" frameborder="0" style="width: 50px; height: 50px;" class="twitter-follow-button" src="' . $url . '"></iframe>', $menu ); return $menu; }
The first line loads a filter on wp_nav_menu. That means this code will work on any theme using custom menus. You can read more about filters in my Genesis Explained series.
Then we get into the guts of the filter. First I build my $url. I’m not going to get into all of that, you can read about the htmlspecialchars() function at php.net. Short version, it converts everything into code that will work in the iframe src correctly.
The next line looks for the html for the “Follow me” link, “Follow me on Twitter
” and then replaces it with my iframe.
Finally I return $menu, which may or may not be edited. It only changes the button it it find the html string I told it to look for.
Armed with this you can replace pretty much anything in your menu with custom code.
nate says
Nick,
Thanks for your time. I, too, am a Christian. How did you learn all this coding lingo? My current site is a total mess and I am just learning how to form the site up (just got it 2 days ago)…it all seems so much to learn:(
Any ideas of how to make it look more professional?
Happy New Year!
In Christ,
Nate
nickthegeek says
I learn by doing, so I setup a test site, then do my best to work things out, break a lot of stuff, then figure out how to fix it. I spend a lot of time reading files to try and figure out how it works.
Keith Bucknall says
Nick,
Where does this code go? Is this in every post or in the functions.php – sorry for being a newbie?
nickthegeek says
Sorry if that wasn’t clear. It goes in the functions.php file.