简体   繁体   中英

Enqueueing jQuery plugin in Wordpress theme template

I made a template called test-stuff.php and tried using jQuery and the jQuery validation plugin in it. I've enqueued the scripts in my functions.php file and the jQuery works fine on other regular pages, but not in my template. Could someone point out where I went wrong? Do I have to enqueue jquery and the jquery plugin separetely for the template? If I have left out some details, please ask and I will provide. Thanks in advance.

functions.php enqueuing part:

function my_custom_queue() {
    wp_enqueue_script('jquery');
    wp_enqueue_script( 'validatejq', 'https://cdnjs.cloudflare.com/ajax/libs/jquery-validate/1.19.0/jquery.validate.min.js', array( 'jquery' ), '1' );
}
add_action( 'wp_enqueue_scripts', 'my_custom_queue' );

Template file with jquery testing function(I get "no"):

<?php 

/* Template name: Test stuff */

?>
<script>
window.onload = function() {
    /* test */
    if (window.jQuery) {
        alert("Yes");
    } else {
        alert("No");
    }
};

</script>

As far as I know, you don't need to enqueue, it is already enqueue by WordPress. Check some of the already included JS libraries. You have not called get_header() and get_footer() either.

You can check out the following link to get the list of already include libraries.

https://developer.wordpress.org/reference/functions/wp_enqueue_script/

You should use get_header() in your page template in order get the header code (including the enqueued scripts) in your page. And you probably want to use get_footer() too. Some scripts are included in the footer.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM