Add Twitter Button To Nav Menu

This tutorial shows you how to display a twitter follow button with counter in your nav menu.

This code works in any WordPress theme however you may need to change the menu classes.

There’s 3 simple steps:

  1. Load the Twitter Javascript file
  2. Filter the wp nav menu
  3. Add CSS for positioning

The code also enables you to show or hide your twitter handle, followers count and change the size of the button to small, medium or large.

twitter-button

Tested on the Genesis Sample child theme by StudioPress.

Here’s the step by step instructions and code for logged in members:

1. Load Javascript

There’s 2 steps needed to load the Twitter Javascript. PHP code to load the script and Javascript added to a file.

(i) Add to functions file.

add_action( 'wp_enqueue_scripts', 'enqueue_scripts_styles' );
function enqueue_scripts_styles() {
    wp_enqueue_script( 'twitter-menu', get_stylesheet_directory_uri() . '/js/twitter.js', array( 'jquery' ), '1.0.0' );
}

(ii) Using a code editor, create a file named twitter.js in child themes js folder and add the following Javascript:

jQuery(function( $ ){
window.twttr = (function(d, s, id) {
  var js, fjs = d.getElementsByTagName(s)[0],
    t = window.twttr || {};
  if (d.getElementById(id)) return t;
  js = d.createElement(s);
  js.id = id;
  js.src = "https://platform.twitter.com/widgets.js";
  fjs.parentNode.insertBefore(js, fjs);
 
  t._e = [];
  t.ready = function(f) {
    t._e.push(f);
  };
 
  return t;
}(document, "script", "twitter-wjs"));
});

2. Filter Nav Menu

Add to functions file.

Was This Tutorial Helpful?

Free

$0

Access only to all free tutorials per month.



Monthly

$75

Access to 10 premium tutorials per month.


Tutorial Request


Includes code guarantee and coding support.

Yearly

$500

Access to 15 premium tutorials per month.


Monthly Tutorial Request


Includes code guarantee and priority coding support.