Including jQuery in WordPress

I am using the code below to include jQuery in my WordPress installation. I was previous calling the jQuery file using the standard HTML script but this was causing problems with a WordPress plugin in IE9. When I use the wp_enqueue_script function, it solves the problem but then it breaks my custom Javascript file which I include after wp_head(). What am I doing wrong?

<?php wp_enqueue_script("/wp-content/themes/mytheme/js/jquery-1.5.1.min.js"); ?>
<?php wp_head(); ?>
<script type="text/javascript" src="/wp-content/themes/mytheme/js/custom.js"></script>

Related posts

Leave a Reply

2 comments

  1. 1) Only include scripts via wp_head(). For your custom script, register and enqueue it as such:

    function mytheme_custom_scripts() {
    
        if ( ! is_admin() ) {
            $scriptsrc = get_stylesheet_directory_uri() . '/js/';
            wp_register_script( 'mytheme_custom', $scriptsrc . 'custom.js' );   
            wp_enqueue_script( 'mytheme_custom' );
        }
    
    }
    add_action( 'after_setup_theme', 'mytheme_custom_scripts' );
    

    2) You need to deregister core jQuery, and then register and enqueue your minified version, like such:

    function mytheme_minified_jquery() {
    
        if ( ! is_admin() ) {
            wp_deregister_script( 'jquery' );
            wp_register_script( 'jquery', 'http://ajax.googleapis.com/ajax/libs/jquery/1.5.1/jquery.min.js' );  
            wp_enqueue_script( 'jquery' );
        }
    
    }
    add_action( 'init', 'mytheme_minified_jquery', 1000 );
    

    Note that both include a if ( ! is_admin() ) conditional. You don’t want to mess with the scripts that load in the Admin UI.

    Also, my example uses Google for the minified jQuery version. If you want to use your own bundled version, add the SRC to wp_register_script() instead.

  2. Multiple issues here:

    • including external version of jQuery without deregistering version bundled with WP;
    • wrong wp_enqueue_script() usage (incorrect arguments);
    • echoing script yourslef;
    • using template file for all of this.

    Basic example of doing it more properly would be something like this in functions.php of theme:

    add_action( 'wp_enqueue_scripts', 'custom_script' );
    
    function custom_script() {
    
        wp_enqueue_script('custom','/wp-content/themes/mytheme/js/custom.js',array('jquery'));
    }