0

I have a small jQuery snippet that executes when a WordPress post has the body class expired. It hides certain elements and works fine when I am logged in but when I am logged out it keeps throwing a JQuery - $ is not defined error.

var $=jQuery.noConflict();
$(document).ready(function () {
    jQuery(function ($) {
        if ($("body").hasClass("expired")) {
            $('.button-link').css('display', 'none !important');
            $(".countdown-wrapper").hide();
            $(".button-link").hide();
            $(".size-default").hide();
    }
    });
});

Any WordPress experts out there could maybe point me in the right direction?

Rob
  • 55
  • 5

2 Answers2

0

Try this

(function ($) {//use $ and expect something
    $(document).ready(function () {
        if ($("body").hasClass("expired")) {
            $('.button-link').css('display', 'none !important');
            $(".countdown-wrapper").hide();
            $(".button-link").hide();
            $(".size-default").hide();
        }
    });

})(jQuery);//pass jQuery

You can read about that here

angel.bonev
  • 1,477
  • 1
  • 13
  • 21
  • Thank you, I found the problem and I should have checked this before I posted. jQuery file was being deferred so my code was loading before jQuery which was causing the problem. – Rob Oct 11 '19 at 13:47
0

Step 1: Inclusion of jQuery Library

wp_enqueue_script( 'YOUR-JS_NAME', get_template_directory_uri() .'/js/YOUR-JS_NAME.js', array('jquery'), '1.0', true );

Step 2: Structure of JavaScript File

(function($) {
    var $=jQuery.noConflict();
    $(document).ready(function () {
        jQuery(function ($) {
            if ($("body").hasClass("expired")) {
                $('.button-link').css('display', 'none !important');
                $(".countdown-wrapper").hide();
                $(".button-link").hide();
                $(".size-default").hide();
        }
        });
    });
})(jQuery);

Step 3: Ensure that jQuery is Loaded

<script src="http://code.jquery.com/jquery-1.11.2.min.js" type="text/javascript"></script>
utsav tilava
  • 124
  • 8