Incorporate jquery into WordPress
I am trying to incorporate a very simple audio player into WordPress that uses jQuery to control the player and the player control background image. There will be several instances of the player on a single page.
I have no problem writing the code for an HTML page, but it doesn't work inside a WordPress page. I've been Googling for a couple hours, but haven't found the specific, understandable answer I need, so I apologize if this has been covered elsewhere.
I don't want to write a plugin, I just want to be able to create a little control over the HTML5 audio player.
The script code:
$(document).ready(function(){
var allAudioEls = $('audio');
function pauseAllAudio(){
$('.gac_play').attr('src', 'play16.png');
allAudioEls.each(function() {
var a = $(this).get(0);
a.pause();
});
}
$(".gac_play").click(function(){
var song = $(this).next('audio').get(0);
if(song.paused){
pauseAllAudio();
$(this).attr('src', 'pause16.png');
song.play();
}else{
pauseAllAudio();
$(this).attr('src', 'play16.png');
}
});
The HTML:
<img class="gac_play" src="play16.png" />
<audio>
<source src="audio/fm-sample1.mp3" />
<source src="audio/fm-sample1.ogg" />
</audio>
Works perfectly on an HTML page, but not in WordPress. Any assistance would be very much appreciated.
Solutions
If I understand correctly, JQuery is a JavaScript library. It will not work in WordPress because that site does not allow JavaScript.
They describe their reasoning somewhere in their documentation. The basic intent is to minimize site security risks and avoid the good old days of MySpace...
Your best option would be to implement the same behavior in PHP.
Make sure you're enqueueing the jQuery file properly and to use your ready function as such:
jQuery(document).ready(function($){
// your code goes here
});
Or you can use
$=jQuery.noConflict();
in the beginning of the script tag. You can check for other errors in the JS console (
Ctrl+Shift+J on chrome
).