Home>Support>Add dynamic JS to footer

Add dynamic JS to footer

By roya, 8 years ago. Last reply by roya, 8 years ago.

Hi there,

I am coding some custom widgets. Right now I am building a slider, which has settings like speed and number of slides visible at once. So these settings need to be written into a js in the footer of the website.

I tried to use the wp_hook

function sliderscripts() {
global $sliderscript;
return $sliderscript;
}
add_action( ‘wp_footer’, ‘sliderscripts’, 100);
?>

the $sliderscript is the final code and just needs to be echoed. The sliderscript is generated in the template.php file below the html output. But the code won’t be sent to the footer. Can you please tell me, how to generate JS and write it to footer with variables set in the siteorigin widget?

Thank you!

This is our free support forum. Replies can take several days. If you need fast email support, please purchase a SiteOrigin Premium license.

  1. 8 years, 2 months ago Greg Priday
    Hi, I Work Here

    Hi Roya

    The best practice way of adding data to scripts is by using wp_localize_script

    https://codex.wordpress.org/Function_Reference/wp_localize_script

    For your code, rather than returning your $sliderscript value, you should be echoing it. Probably between script tags. As a general rule, actions in WordPress must perform the action themselves (in this case, echoing), while filters will generally return a value.

    • 8 years, 2 months ago roya

      HI Greg,

      I have a question, as I did not know this function. It seems, that I can add attributes (like the sliders speed), thats awesome so far. But bxslider starts with an ID or class, f.e.
      $(‘.bxslider’).bxSlider({
      or
      $(‘#bxslider’).bxSlider({

      As I need multiple sliders per page, the ID must be unique, so I can’t prefill it. I solved it so far with “$sliderid = uniqid();”. But I can’t pass the ID to the wp_localize_script as it is no attribute, it’s the catcher. Or can I and just oversee / dont understand it?

      Thank you!

    • 8 years, 2 months ago roya

      Hi Greg,

      you made my day. That’s the solution I’ve been looking for. Thank you so much!

      all the best

  2. 8 years, 2 months ago roya

    Thanks for your fast reply! I’ll add it to the template-file (right?) tomorrow. I can’t access the FTP right now to test it out. I will give you feedback.

Replies on this thread are closed. Please create a new thread if you have a question, or purchase a SiteOrigin Premium license if you need one-on-one email support.

Get The Most Out of SiteOrigin with SiteOrigin Premium

Find Out More