Probably there are a lot of questions/answers here in wpse that explain this kind of issues and the use of jquery and other js in wordpress.
However,
- In wordpress never put javascripts in template files. Javascript should be in separate .js files.
- The javascript should be putted in the templates using
wp_register_script
/wp_enqueue_script
functions using the hookwp_enqueue_scripts
- If one have to pass php variables to js (that being in js files cannot contain
<?php echo $something ?>
the functionwp_localize_script
should be used
This is valid for all javascript files / libraries.
Regarding jQuery
- Always use the jQuery version embedded in WordPress using
wp_enqueue_script('jquery')
, everytime you deregister jQuery and register a cdn-version of it a cat die. And a dog feels bad. - Once we use jQuery embedded in WordPress, it works in
noConflict
mode, so the$
alias doesn’t works until we use one of the noConflict wrappers
Docs
- wp_register_script function
- wp_enqueue_script function
- wp_enqueue_scripts hook
- wp_localize_script function
I’ll use your case as example to better explain these arguments.
First you have to create a javascript file, call it “templateportfolio.js” and save it in ‘js’ folder of your theme, and put your js code there, remember to use noConflict wrappers:
jQuery(document).ready( function($){
$(".logobutton").hover(
function() { $(this).attr("src", my_script_data.logobutton_hover); },
function() { $(this).attr("src", my_script_data.logobutton); }
);
});
Here there are here 2 variables: my_script_data.logobutton_hover
and my_script_data.logobutton
that you need to pass to the script with wp_localize_script
.
In fact, in function.php
, you have to enqueue the script only for the page template and use wp_localize_script
to pass the url of images:
function enqueue_templateportfolio_js() {
// change the template file name according to your file
if ( ! is_page_template('templateportfolio.php') ) return;
wp_enqueue_script('enqueue_templateportfolio_js', get_template_directory_uri() . '/js/templateportfolio.js', array('jquery'), null, true );
$imagesurl = get_template_directori_uri() . '/images/';
$images = array(
'logobutton_hover' => $imagesurl . 'logobutton_hover50pc.png',
'logobutton' => $imagesurl . 'logobutton50pc.png',
);
wp_localize_script('enqueue_templateportfolio_js', 'my_script_data', $images );
}
add_action('wp_enqueue_scripts','enqueue_templateportfolio_js');