1

So, I have a custom Javascript code that inserts a pop-up widget in a webpage. The source code is irrelevant but it works by manually pasting before the <\body> tag of the website, such that:

<body>
   /*
   do something
   */
   <script type="text/javascript" id="widget-code">
       /*
       widget pops up
       */
   </script>
<\body>

What I want to do is include that script in the plugin that I'm developing so that the widget will appear in all webpages of the Wordpress site. How do I do such?

/**
* Plugin Name: Test Plugin
* Plugin URI: http://example.com
* Description: test plugin
* Author: John Doe
**/

If I'm not mistaken, this is essentially a task of pasting the script before the <\body> tag in all webpages but inside a plugin?

1

1 Answer 1

2

Look into wp_register_script() and wp_enqueue_script(). You may be able to get by with only the latter.

Pay special attention for your case of wanting it before the closing </body> that you can specify in_footer as a parameter.

wp_enqueue_script(  $handle, //(string) name of script
                    $src = '', // uri to script
                    $deps = array(), //handles of other scripts this script is dependent on
                    $ver = '1.0', version number of script 
                    $in_footer = true //if script should be in footer
                   )

You can hook the above via the wp_enqueue_scripts hook

function enqueue_your_scripts() {

    wp_enqueue_script( 'script-name', plugin_dir_url( __FILE__ )  . '/js/example.js', array(), '1.0.0', true );
}
add_action( 'wp_enqueue_scripts', 'enqueue_your_scripts' );

In the above, plugin_dir_url( __FILE__ ) is returning the plugin directory the file is in, and we're assuming a subdirectory of /js/ and a file named example.js

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.