0

Is there any filter or hook to print a script or add in the footer some content? I'm not talking about wp_enqueue_ function, I'm creating a plugin that will show a banner for privacy and cookie info and I want to append it to the footer. I'm using at the moment this code, but I hope that there is a more clean wey to do it:


function cookie_privacy_script()
{
<script>
// js code here
</script>
}
add_action('wp_enqueue_scripts', 'cookie_privacy_script');

2 Answers 2

0

Printing content and adding a script to the footer are two different things.

If you want to add your banner html in the footer, you can use the wp_footer hook that will trigger when you call the get_footer() function from your theme.

You can simple echo your html (or load a template file).

function myplugin_wp_footer () {
    echo '<div id="myplugin-cookie-banner">bla bla</div>';
    // or you can use include() function to load a PHP script instead
}
add_action('wp_footer', 'myplugin_wp_footer');

Then you can add your JS script as suggested by @CRavon

function myplugin_cookie_privacy_script(){
  wp_enqueue_script( 'myplugin-cookie-script', plugin_dir_url(__FILE__).'js/cookie-banner.js', [], true, true);
}
add_action('wp_enqueue_scripts', 'myplugin_cookie_privacy_script');

The last parameter of wp_enqueue_script tells that your script will be added in the HTML at the end of the body.

0

Yes there is a cleaner way of loading script in footer : use function wp_enqueue_script with the last argument $in_footer set to true. So your code will look like so :

function cookie_privacy_script(){
  wp_enqueue_script( 'your_script_name', path/to/your/script/on/server, '[dependencies, if, any]', true, true);
}
add_action('wp_enqueue_scripts', 'cookie_privacy_script');

You will have to change "path/to/your/script/on/server" with the actual path of your script and '[dependencies, if, any]' by an array of dependencies of this script.

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.