1

This is rather basic, and maybe it's a duplicate question, so let me know where exactly is answered in that case.

I need to add a very simple jQuery script inside my Page Template. I'm using Openstrap theme and I can see that jQuery is loaded on every page, so I thought I could insert my script normally but doesn't work.

After reading some posts, I've seen that I have to use wp_enqueued_script function, however I just need to load the script on the Page Template only, not every page.


edit

It worked! I changed it to is_singular($post_type) for my needs, and it works as expected. However, the jQuery script isn't doing anything.

Inside functions.php,

/* loader iframes */
function loader_iframe() {
if ( is_singular('farmacia') ) {
        wp_enqueue_script( 'loader-iframe', get_template_directory_uri() . '/js/loader-iframe.js', array( 'jquery' ));
    }
}

add_action( 'wp_enqueue_scripts', 'loader_iframe' );

Inside js/loader-iframe.js,

$(function() {
    $('.loader-iframe').on('load', function(){
        $('.loader-iframe').find('img').hide();
    });
});
3

You should use the wp_enqueue_script() function to first enqueue your script and then wp_enqueue_scripts action hook to properly add your script to your footer or header of your theme.

Also, you should take a look at conditional tags and how they are used to load functions/scripts/styles/etc on a conditional basis.

So you would do something like this. First create a new file in your themes js folder and call it something like my-script.js. Open in up and add your scripts into that file. You are now ready to add the js file to your theme's header/footer conditionally on a specific page with this function

function enqueue_my_scripts() {
if ( is_page( 42 ) //will check if we are on page ID 42, please see conditional tags or is_page_template( 'about.php' ) to check if the page template is about.php ) {
        wp_enqueue_script( 'my-script', get_template_directory_uri() . '/js/my-script.js', array( 'jquery' )//only if script is dependant on jquery );
    }
}

add_action( 'wp_enqueue_scripts', 'enqueue_my_scripts' );
  • thanks, I read something about that, but you made it very clear! – whitenoisedb Jun 16 '14 at 22:43

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.