Quantcast
Channel: Shinra Web Holdings » wordpress
Viewing all articles
Browse latest Browse all 10

Proper way to add a Superfish Menu to a WordPress Theme

$
0
0

If you’ve ever coded the CSS and/or JavaScript needed to make a WordPress nav menu work smoothly across all browsers, you know how daunting that can be. Superfish is a jQuery plugin that is really ideal for WordPress’s multilevel navigation menus. Many themes make use of it, but (I’m assuming due to the lack of quality tutorials) few of them do it correctly. I will outline the correct procedure for adding Superfish, oh any other jQuery plugin to your theme.

Enqueue Scripts and Styles

Create a function that enqueues the necessary files. It’s generally a bad idea to replace WordPress’s native jQuery file, so don’t do it unless you absolutely must to make it work. I’ve included the (disabled) code to do it just in case you’re forced to.

function themeslug_enqueue_superfish() {
// set the directory holding the superfish files
    $sf_dir = trailingslashit( get_stylesheet_directory_uri() ) . 'sf/';

// don't do this if you can help it
    $reload_jquery = false;
    if( $reload_jquery ) {
        wp_deregister_script( 'jquery' );
        wp_enqueue_script( 'jquery', . $sf_dir . 'jquery-1.8.1.min.js', 'json2', '1.8.1' );
    }

// queue up superfish
    wp_enqueue_script( 'hoverIntent', $sf_dir . 'hoverIntent.js', 'jquery' );
    wp_enqueue_script( 'superfish', $sf_dir . 'superfish.js', 'jquery', '1.4.8' );
    wp_enqueue_style( 'superfish', $sf_dir . 'superfish.css', false, '1.4.8' );
}

add_action( 'wp_enqueue_scripts', 'themeslug_enqueue_superfish', 0 );

Proper Initialization

The superfish code should be called using safe wrappers, and only after the document is loaded. Use the following function and hook to accomplish this:

// load jquery on page ready
function themeslug_init_superfish() {
echo '<script type="text/javascript">jQuery(document).ready(function(){
jQuery(\'ul.sf-menu\').superfish();});</script>';
}

add_action( 'wp_head', 'themeslug_init_superfish', 99999 );

Make sure your nav-menu uses the .sf-menu class as a wrapper, then edit the superfish.css file to match your theme’s style. That’s it!


Viewing all articles
Browse latest Browse all 10

Trending Articles