This thread is over two years old and may be outdated. Please create a new thread if you need help, or email us if you have an active Premium license.

Add dynamic JS to footer

9 years ago · Last reply by roya 9 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.

Need fast email support? Get SiteOrigin Premium

Replies

4
  1. Greg Priday Staff 9 years, 6 months ago

    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.

    • roya 9 years, 6 months ago

      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!

    • roya 9 years, 6 months ago

      Hi Greg,

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

      all the best

  2. roya 9 years, 6 months ago

    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.

Have a different question or issue?

Start New Thread