• I wrote a jQuery script for my WordPress plugin, and it looks like this:


      $(function() { // jQuery code here });

      Even though I make sure that jQuery is loaded on the page, I keep getting the following error in the browser console:

      TypeError: $ is not a function

      I’ve read that WordPress uses jQuery in no-conflict mode. Should I rewrite my code like this to fix the issue?


      (function($) { // jQuery code here })(jQuery);

      What is the best way to handle this error when working with jQuery in WordPress?

      • Make sure your script is enqueued correctly in WordPress, with jQuery declared as a dependency. Use the following PHP code:

        php
        Copy code
        function enqueue_my_script() {
        wp_enqueue_script(
        ‘my-custom-script’, // Handle name for your script
        plugin_dir_url(__FILE__) . ‘js/my-script.js’, // Path to your script
        array(‘jquery’), // Declare jQuery as a dependency
        ‘1.0.0’, // Version
        true // Load in the footer
        );
        }
        add_action(‘wp_enqueue_scripts’, ‘enqueue_my_script’);

        1