I am using a 3rd party service to render a booking calendar on one of my pages. They don't have an implementation specific for Wordpress. They just provide a couple lines of code and say to put them in the location on your page where the calendar should be rendered. The code looks something like:

<script src="https://app.example.com/widget.js"></script>

Adding this directly to my WP page via a text or html widget works just fine, but i know it's not really the "Wordpress" way of doing things. I know I can easily add the remote .js file using wp_enqueue_script() in an action hooked to wp_enqueue_scripts (with a conditional so it only loads on pages displaying the calendar). That seems simple enough.

It's the next part I'm not entirely sure how to handle. My 1st thought was to put it in a shortcode so that it can be reused on multiple pages:

add_shortcode('booking_cal', 'blx_add_booking_cal');
function blx_add_booking_cal() {
  $out = '<script>Cal.initCalendar(myCalURL)</script>';
  return $out;

and calling [booking_cal] in my page where I want the calendar to appear. This doesn't seem any different from just pasting both snippets into the page as I initially described... with the exception of having to make sure the remote script (instantiating the Cal object) loads first.

The result of Cal.initCalendar(myCalURL) is that an <iframe> with the calendar is created and inserted into the DOM (by appending it to the parent container) wherever that line is called. It would have been nice if that line returned the <iframe> element leaving me free to insert it when and where I please, but alas...

Given the fact that Cal.initCalendar(myCalURL) actually inserts the <iframe> (rather than returning it), is there any advantage to adding something like

$(document).ready(function() {
  var $calWrap = $('.calendar-container');
  if(!$calWrap.length) return;

  var jsStr = '<script>Cal.initCalendar(myCalURL)</script>';
  var $calInner = $('<div/>', { 
    'id': 'demo-booking-calendar',
    'class': 'booking-calendar' 

to my global JavaScript file that is loaded on every page? Or is there a more appropriate way in better keeping with Wordpress best practices that I may want to pursue?

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Browse other questions tagged or ask your own question.