Add script only once for Shortcode and Widget

I’ve written a plugin which loads a JS library in a WordPress post. I’m using a WordPress shortcode to detect a call to the plugin like this : [myplugin class="abc"].

So basically everytime the user writes [myplugin ...], my plugins transforms this string into a <p class="abc"> tag and I’m enqueuing a remote JS script which parses the <p> tag.
I would like to allow the same behavior for a widget sidebar, so the user can write <p class="abc"> in a text widget. All I need is the JS to be loaded.

Read More

Rather than loading this JS lib in the text widget + in every post, I’d rather embed my script only once, every time the WordPress is loaded.

Is saw in akismet code source that they are using the init hook. Is that the right hook to use ?

Related posts

Leave a Reply

1 comment

  1. You may use following code in your plugin (your_plugin.php)

    add_action( 'wp_enqueue_scripts', 'load_my_scripts' );
    function load_my_scripts()
    {
        wp_enqueue_script( 'my_script',  plugins_url( '/js/my_script.js' , __FILE__ ) );
    }
    

    Here, the my_script.js file could be in your plugin’s folder like your_Plugin/js/my_script.js.

    Read more on Codex.