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!
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.
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!
Hi Greg,
you made my day. That’s the solution I’ve been looking for. Thank you so much!
all the best
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.