WordPress Plugin development Call to undefined function jQuery()

You need specify jquery as a dependency of your custom script, setting the 3rd parameter of wp_enqueue_script() to array('jquery'), like this:

wp_enqueue_script(
    'yourCustomScript',
    plugins_url('js/yourCustomScript.js', __FILE__),
    array('jquery'),
    '1.0.0',
    false
);

Change the path to point to your custom-script file

As to your last question, the answer is affirmative. You need a .js file. Basically WP needs to know what scripts are loading in a page to make sure dependencies are loading first and none gets loaded twice.

Also keep in mind that your usual $() alias will not work unless you wrap your code in:

jQuery(document).ready(function($) {
    // Inside of this function, $() will work as an alias for jQuery()
    // and other libraries also using $ will not be accessible under this shortcut
});

Refference.

Here’s a testing example that should work from inside a custom plugin:

jquery-test.js:

jQuery(document).ready(function($) {
    $('<a/>', {
        id: 'foo',
        href: 'https://www.google.com/webhp?q=jquery+mistakes+you+are+probably+making',
        title: 'bar',
        rel: 'external',
        text: 'jQuery\'s dead! Long live jQuery!',
        style: '' +
            'position: fixed;' +
            'top: 120px; ' +
            'left: 0; ' +
            'padding: 10px 20px; ' +
            'background-color: #369; ' +
            'color: white; ' +
            'z-index: 9999;' +
            'border-radius: 0 6px 6px 0'
        })
    .prependTo('body');
});

Put this file in your plugin’s /js folder.
In your plugin’s main file, add this php:

add_action('wp_enqueue_scripts', 'testing_jquery');
function testing_jquery() {
    if ( ! is_admin()) 
        wp_enqueue_script(
            'testing-jquery',
            plugins_url('js/testing-jquery.js', __FILE__ ),
            ['jquery'],
            true
            );
}

Make sure it’s not inside any other function or class.

If you’re not adding this via a plugin, but a theme, place the testing-jquery.js file in the theme’s /js folder and replace plugins_url('js/testing-jquery.js', __FILE__ ), with get_stylesheet_directory_uri() . '/js/testing-jquery.js',

This should add a blue link to a google search for common mistakes when using jQuery to every frontend page of your website.

Leave a Comment