Using jQuery with WordPress

mw022If you’re a theme developer, you’ll (perhaps) be looking at keeping up with the latest in javascript/AJAX and incorporating a few tweaks into your brand new theme – in some ways, it’s been made very easy for you (and in one or two ways it’s just a little tricky…)

So, assuming you have a basic knowledge of PHP, theme design and javascript, here’s how it works:-

Loading up jQuery

WordPress arrives with jQuery already bundled, so this bit’s easy enough. But we need to get it loaded onto the page, which doesn’t happen automatically…

The plan here would be to get some nice tabbed divisions going, maybe in the sidebar, courtesy of jQuery.

<?php
add_action('template_redirect', 'them_js_head_load');

function them_js_head_load(){

 // we don't need this on admin pages, so...
	if(is_admin()) return;

      wp_enqueue_script('tabber', get_bloginfo('template_directory') . '/scripts/tabs.js', array('jquery', 'jquery-ui-core', 'jquery-ui-tabs'), '1.0');
}
 ?>

In this code, we’ve enqueued a custom script tabs.js, that’s going to initiate the whole process – and we’ve also declared its dependencies – jquery, jquery-ui-core, jquery-ui-tabs, the user interface sublibraries, also bundled into WordPress as standard.

These are already registered, so only the handle is required, here: ‘jquery-ui-tabs’, etc.

The full list of bundled libraries is at: WordPress wp_enqueue_script.

Vital! – The snippets of jQuery code you’ll find while out and about on the net make extensive use of the shortcut $ to express the jQuery global object. This isn’t going to work in WordPress, so at all times we use jQuery(document).ready(function($) – and then it will work… Once inside the function, we can use $ as a shortcut.

The reason for this slight complication is that Prototype and Scriptaculous libraries arrived first into WordPress and have got to hold on to using the $ shortcut. And don’t be tempted to dabble with jQuery.noConflict() here – you won’t get good results.

And from here, since you know what you want to put in your theme in terms of flashy javascript/AJAX add-ons, I’ll leave you to get on with thieving some snippets and getting them up and running….

* Update – some of this information is superseded by changes in the way WordPress handles the loading of javascript – there’s a follow-up here – More about WordPress and jQuery

Share:
  • Digg
  • del.icio.us
  • Facebook
  • Mixx
  • Google Bookmarks
  • email
  • LinkedIn
  • Reddit
  • StumbleUpon
  • RSS
  • Twitter

26 Responses to “Using jQuery with WordPress”

  1. Shubham says:

    Hi
    Hope you can help me

    I am trying to have a floating div block. For that i Have done following:

    In header.php (using jQuery):

    $(document).ready(function()
    {
    $(window).scroll(function()
    {
    $(‘#globalnav’).animate({top:$(window).scrollTop()+”px” },{queue: false, duration: 350});
    });

    $(‘#close_message’).click(function()
    {
    //the messagebox gets scrool down with top property and gets hidden with zero opacity
    $(‘#globalnav’).animate({ top:”+=15px”,opacity:0 }, “slow”);
    });
    });

    Issue:
    This works perfectly on the landing page of the blog but on the individual post page the same thing doesn’t work. It shows me the globalnav menu but it neither scrolls nor closes.

  2. Daniel says:

    so this is my code

    <link rel=”stylesheet” href=”" type=”text/css” media=”screen” />
    <link rel=”alternate” type=”application/rss+xml” title=” RSS Feed” href=”" />
    <link rel=”alternate” type=”application/atom+xml” title=” Atom Feed” href=”" />
    <link rel=”pingback” href=”" />

    jQuery(document).ready(function(){
    $(‘.mainlinks li a’).click(function() {
    $(‘.mainlinks li a’).removeClass(’selected’);
    $(this).addClass(’selected’);
    });
    });

    the im thinking the problem has to do with the order in which the code is loading. my script is before jquery is loaded. however i really don’t know.

    I had it working not in wp but cannot get it working in wp… any ideas

    Daniel’s last blog post..wow

    • Daniel says:

      ok that didn’t turn out so well. you have a filter on the code essentially making it unreadable…

      php wp_enqueue_script( ‘jquery’ );

      php if ( is_singular() ) wp_enqueue_script( ‘comment-reply’ );

      script type=”text/javascript”>
      jQuery(document).ready(function(){
      $(‘.mainlinks li a’).click(function() {
      $(‘.mainlinks li a’).removeClass(’selected’);
      $(this).addClass(’selected’);
      });
      });
      </script

      php wp_head();

      that is the code with all the proper tags of course

      • lisa says:

        From that code the js should be being output after the jQuery call – which, you’re right, it does need to be. You might try putting it in a file, and enqueuing it with a dependence on jQuery

        • beasleyq says:

          Try putting this:

          script type=”text/javascript”>
          jQuery(document).ready(function(){
          $(’.mainlinks li a’).click(function() {
          $(’.mainlinks li a’).removeClass(’selected’);
          $(this).addClass(’selected’);
          });
          });

          after the php wp_head();

  3. Ifthikhan says:

    Hi…all
    i am not femiliar with javascript
    my client ask to impliment something like the following site
    album pls visit desertgroup.ae/en/section/project-portfolio and move mouse on the image. any one can help me. thanks in advance

  4. Nick Nielsen says:

    Thanks for this piece of info !

    It helped me set up Ajaxify on my site. I posted a link here on the Ajaxify support page.

    It also frees me up to experiment with jQuery elsewhere in the code.

    I hope you keep up the good work – and a long and productive life for your site.

  5. Edward says:

    This post is extremely informative. I never knew that wordpress2.7+ came with jquery. However, after reading the post for 100 times i couldn’t figure out where exactly to put the “”
    text to make it all work.

    After putting it in my it added jquery but also doubled all the other meta links that i alleady had, upon load(not sure if that’s a good thing).
    Please help.

  6. Craig says:

    Thanks for posting. Just got it to work much faster than I anticipated.

  7. Blutarsky says:

    Hi there, I’m using jQuery to inject content into my index.php, in asynchronous mode.

    The jQuery loaded .php file, lying in the same folder as index.php, makes a call to a function of an installed plugin.
    Problem is I get a “call to undefined function” error, whilst if the same function call is made within index.php, it works.

    I’m starting to believe that the loaded .php document with Jquery is done in such a way that Worpdress is tricked, so the function call fails. Could it be that executing a call to JQuery, will change the environemnt or the current folder?

    Heres the code:

    jQuery.noConflict();
    jQuery(“#foo”).load(“/wp-content/themes/tgv1/topposts.php”);

    • Lisa says:

      At a guess, if it’s a WP function not existing, you’re not loading the WP environment into the ajax php script

      require_once(PATH TO.’/wp-load.php’);

  8. UzEE says:

    Hi,

    I’m planning to use jQuery and jQuery UI in a theme I’m building (UI for the Admin pages). I’m using the entire package of the jQuery UI with all widgets and everything along with a custom theme.

    If I enqueue my own versions of the script, won’t that conflict with those built into Wordpress?

  9. Amir Swaleh says:

    Heey Thanks for this solution.

    This really helped me out. Because I was stuck on a really simple fadeout thingie.

    I never knew you could use something like a jquery.noconflict.

    thanks again!!!!

  10. MItch says:

    Im having a jquery conflict on my feature content glider! The glider jquery is conflicting with photosmash galleries and lightbox-pro in wordpress.mu root page. can you help me

  11. Jonna says:

    Thanks for the post! Now I can load my custom jQuery scripts.

  12. irina says:

    many thanks – great tutorial!! worked on the first click – almost first time in my life!

  13. John says:

    Very helpful, thanks. I was struggling to make the “ready” function work.

  14. Thomas says:

    Thank you for this! Knowing that WordPress has jQuery built in makes my life a bit easier. Until I need to use something cutting-edge, that is…

  15. Irfan Mansha says:

    Hi,

    I like the way u have shown source code. I want to know that which plugin u have used to display the source code.

    Thanks,

  16. joomlawind says:

    Thanks for the detailed explanation of source code……..

  17. Andre says:

    Just to point out that the jquery noConflict does work in wordpress 2.x
    by doing $jq = jQuery.noConflict(); or if that fails then
    $jq = jQuery.noConflict(true);

    It has worked for me two different wordpress 2.x installations.

Trackbacks

  1. JQuery navigation with jpgs « How To
  2. Using jQuery with WordPress | Themocracy WordPress Themes « My Snippet Library
  3. Celebrate jQuery in WordPress and WordPress Plugins: jQuery Turns 4 | WordCast - Blogging news, WordPress help, WordPress plugins, WordPress themes, WordPress news

Leave a Reply