spas2k spas2k - 4 months ago 9
Javascript Question

wordpress - jQuery doesn't work in plug in, but works everywhere else?

Sorry for the easy question, (hey, easy rep!) but I'm new to PHP as of 1 day. I have to create a wordpress plugin/widget out of necessity. I have en queued jquery in my header:

`<?php wp_enqueue_script("jquery"); ?>`


and created a class intended to be clicked in the plugin.

jQuery('.court').click(function () {
alert(jQuery(this).attr('id'));
});


Simple stuff and it works if I place the code within the footer (which has nothing else in it but some JQ). It does NOT work if it's inside the plugin. Javascript alert('boom'); does work in the plugin.

What am I missing in order to use jquery within the plugin? I obviously don't want to put it in the footer since it won't be packaged there.

Answer

I have to create a wordpress plugin/widget out of necessity. Are you writing a Plugin from Scratch? If so; try adding the code below anywhere in your Plugin's Main File:

    <?php
        function myPluginScripts() {
            wp_enqueue_script( 'jquery-my-plugin', get_site_url() . "/wp-includes/js/jquery/jquery.js", array(), '');

            // IN THIS FUNCTION, YOU CAN ADD OTHER JS FILES AS WELL LIKE SO 
            // UNCOMMENT THE LINE BELOW & CHANGE THE VALUES IF YOU NEED TO
            // wp_enqueue_script( 'my-plg-js', 'path/to/my-plg.js', array('jquery'), '');
       }

       add_action('wp_enqueue_scripts', 'myPluginScripts');