0

I'm trying to create and test my first basic WP plugin with some difficulty. I am also running a WAMP server.

Below are the scripts utilized.

The html is the only script added to a page through WP's page edit window. The php is from a file (whose content can also be seen through the Plugin edit window within WP) saved in the plugin/test_plugin directory. The javascript is saved in a file within the same test_plugin directory as the php file.

Side notes:

The plugin has been "activated" in the main WP Plugin window. Identical (except for file storage locations, names, script name, etc.) have been previously inserted into the theme's function.php file along with associated js files being made available that HAVE demostrated the desired feature.

What am I doing wrong??

html

<button id="unique_button" type="button">Click Me!</button>

--

test_plugin.php

<?php
    /*
    Plugin Name: test_plugin
    */

 function test_plugin() {
    wp_enqueue_script( 'change_button', get_template_directory_uri() .  'change_button.js', array( 'jquery' ), '1.0.0', 1 );
}

add_action( 'wp_enqueue_scripts', 'test_plugin' );

?>

--

change_button.js

jQuery( function ( $ ) {
    $("#unique_button").click(function() {
        $(this).fadeOut(1000);
    })
});
0

1 Answer 1

3

When enqueuing JavaScript or CSS from a plugin's directory, use plugin_dir_url( __FILE__ ).

Note that plugin_dir_url() does return the URL with a trailing slash, unlike get_template_directory_uri() and get_stylesheet_directory_uri() which do not return the URL with a trailing slash. get_template_directory_uri() and get_stylesheet_directory_uri() are more commonly used in themes and child themes respectively.

Here is an updated version of test_plugin(). It works.

add_action( 'wp_enqueue_scripts', 'test_plugin' );
function test_plugin() {
    wp_enqueue_script( 'change_button', plugin_dir_url( __FILE__ ) .  'change_button.js', array( 'jquery' ), '1.0.0', 1 );
}

There was also a small fix needed for the JavaScript. #unique_button should be in quotes. Finally, it's a best practice to use .on() instead of .click().

change_button.js:

jQuery( function ( $ ) {
    $( "#unique_button" ).on( "click", function( e ) {
            $(this).fadeOut(1000);
    });
});

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.