简体   繁体   中英

Enqueueing Javascript and jQuery in a Wordpress plugin

I am a beginner to PHP and I'm trying and failing to get it to cooperate in loading a basic test alert in Javascript/jQuery. I'm creating a plugin for a Wordpress site and I just need to make sure that I can successfully run Javascript programs on the page before I can really start writing for it. Here is what I have so far:

The .js file is just a test alert, written with jQuery.

$(document).ready(function () {

    alert("Your plugin's working");

});

The PHP file is an extremely simple plugin designed to run the alert.

<?php
/**
 * Plugin Name: PanoramaJKM
 * Plugin URI: unknown
 * Description: Should alert on loading
 * Version: 0.1
 * Author: Matt Rosenthal
 * Author URI: unknown
 */

    function loadQuery() {
        if (!is_admin()) {
            wp_enqueue_script('jquery');
        }
    }

    add_action('init', 'loadQuery');


    function headsUp() {
        wp_enqueue_script('alert-js', plugins_url('/js/alert.js', __FILE__), array('jquery'));
    }

    add_action('wp_enqueue_scripts', 'headsUp');
?>

Whenever I attempt to load the plugin on my Wordpress site, the JS console spits this error at me:

Uncaught TypeError: undefined is not a function 

I can get the JS alert to show if I change my alert.js file to be without jQuery. However, I need jQuery to write the final plugin and I feel like I'm missing something that's easily fixable. Any help would be greatly appreciated! I've already tried following the advice of other SO posts and a couple of online guides with no success.

WordPress loads jQuery in noconflict mode because it ships with Prototype as well. So, you can't refer to jQuery with $, you need to spell out jQuery. Your Javascript code needs to be:

jQuery(document).ready(function () {
    alert("Your plugin's working");
});

Alternately, you can wrap your code in a self-executiing anonymous function which defines $ inside of it:

(function($) {
    $(document).ready(function () {
        alert("Your plugin's working");
    });
})(jQuery);

Dave Ross' answer is spot on. I'll add that, this is the most common format:

jQuery(document).ready(function($) // <-- $ as shortcut for jQuery
{   
    alert("Your plugin's working");
});

And you don't need add_action('init', 'loadQuery'); . jQuery is already being loaded as a dependency for alert-js and the correct place to enqueue is the action hook wp_enqueue_scripts (which only runs on the frontend).

I believe there is an issue using $ in wordpress. Try using jQuery(document).ready(....

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