“undefined is not a function” when I add a WordPre

2019-08-02 23:04发布

I'm creating a website with my own jQuery and two plugins (jCarousel, Cycle2), and other two from WordPress (Advanced Custom Fields and CPT UI). It has been running smoothly, but now when I try to add a new WordPress plugin (I've tried both Contact Form 7 and Kento Ajax Contact Form), I get the "undefined is not a function" error, marked at the last line of the following piece of code:

// Set jCarousel configuration
        $(function() {
            var hash = 0;

            if (window.location.hash) {
                hash = parseInt(window.location.hash.slice(1));
                hash--;
            }

            $('.jcarousel').on('jcarousel:createend', function() {
                $(this).jcarousel('scroll', hash, false);
            }).jcarousel(); 

(After that piece of code I have a lot of more jCarousel configuration, but I end it properly with }); when I'm done).

I've got several pieces of jQuery encapsulated within $(function() { /* code here */ }); , one before the jCarousel configuration and 7 after, is there any problem with that?

I've already tried to change $ to jQuery and also the following code:

e(function ($) { $(document); }(jQuery));

What else can I try to solve this problem?

1条回答
Root(大扎)
2楼-- · 2019-08-02 23:59

I found the problem. I was loading jQuery on the of my header.php file like this:

<script src="<?php bloginfo('template_url'); ?>/scripts/jquery.min.js" type="text/javascript"></script>

This caused jQuery to be loaded twice, because the plugins were enqueuing it. I had to properly include jQuery and the plugins like this:

function load_plugins() {
if (!is_admin()) {
    wp_deregister_script('jquery');
    wp_register_script('jquery', 'http://ajax.googleapis.com/ajax/libs/jquery/1/jquery.min.js', false, '1.11.1', true);
    wp_enqueue_script('jquery');

    wp_enqueue_script('cycle2', 'http://malsup.github.com/jquery.cycle2.js', array('jquery'));
    wp_enqueue_script('jcarousel', get_template_directory_uri() . '/js/jquery.jcarousel.min.js', array('jquery'));
} } add_action('init', 'load_plugins');

And then encapsulate my jQuery code on the footer like this:

(function($) {
    /* jQuery code here */
}(jQuery));
查看更多
登录 后发表回答