So everything with jquery and wordpress works smoothly if you’re using plugins downloaded from the codex. Genreally these plugins use their own version of jquery min and get along quite well. But what happens if you want to put a custom script in your theme and NOT use a plugin? It can be quite frustrating.
So here is a use case scenario. I wanted to have a sliding featured content section on a landing page for this theme I was building. I had it working but wanted to use the google version of jquery min to minimize load on my server. I chose easySlider because I have used it before and its very easy to use. Here is how I got it working in my theme.
First step, in your functions.php deregister wordpress jquery and register google jquery:
<?php
function my_init_method() {
wp_deregister_script( ‘jquery’ );
wp_register_script( ‘jquery’
, ‘http://ajax.googleapis.com/ajax/libs/jquery/1.4/jquery.min.js’);
}
add_action(‘init’, ‘my_init_method’);
?>
Second step, use the wp_ enqueue_script in header.php:
<?php wp_enqueue_script(‘easySlider’, get_bloginfo(‘stylesheet_directory’) . ‘/js/easySlider1.7.js’, array(‘jquery’), true); ?>
I put the easySlider js in a js folder inside of my theme directory. I use the stylesheet_directory location though you can also use the template_directory location.
Thirdly, add in your custom strings:
This is where I got tripped up. I kept trying to use the examples and it wasnt working. I was getting an error that said “$ is not a valid function”. I scoured the net for a solution and came across a useful tip from devoracles:
The jQuery team was smart enough to realize that there will be conflicts between frameworks, especially the $ will cause massive headaches since it’s the basic of each framework. $ is the shortcut for the word “jQuery”
That was the missing key! I just had to change the function reference in the custom array from “$” to “jQuery”. Here is an example of my code:
<script type=”text/javascript”>
jQuery(document).ready(function(){
jQuery(“#slider”).easySlider({
auto: true,
continuous: true,
speed: 400,
pause: 9000,
numeric: true,
numericId: ‘controls’
});
});
</script>
After that, it worked! And I had a new method for adding custom scripts to my wordpress themes!
I hope this helps. I am not the best at javascript, but I know enough to get myself in trouble. Feel free to leave me comments with ideas and corrections.