Add JS in footer via shortcode?

I have created a shortcode that does some PHP processing, and then returns some javascript; current code is as follows:

<?php
add_shortcode( ’round_time_to_next_15_min_interval’, ’round_time_to_next_15_min_interval’ );

function round_time_to_next_15_min_interval() {

// get current date & time
$current_date = date(‘d-M-Y g:i:s A’);
$current_time = strtotime($current_date);

// create new date & time that is the nearest next 15 minute interval
$frac = 900;
$r = $current_time % $frac;
$new_time = $current_time + ($frac-$r);
$new_date = date(‘d-M-Y g:i:s A’, $new_time);

// JS script to localize time for user & insert result into form field
$html_out = “<script>
var date = new Date(‘” . $new_date . ” UTC’);
var NextWebinarTime = date.toLocaleString();
// document.getElementById(‘webinartime’).innerHTML = NextWebinarTime;
document.querySelector(‘[value=”Next Webinar Time:”]’).innerHTML = NextWebinarTime;
</script>
“;

// return script
return $html_out;

}
?>

Currently, as expected, the shortcode spits the code out in exactly the place the shortcode is used.

What I would like to do instead is cause it to place the JS script in the footer of the page, but I can’t figure out how to factor that in to my current code.

Read more here:: Add JS in footer via shortcode?

Leave a Reply

Your email address will not be published. Required fields are marked *