Add script in footer at specific hours of the day in php

53 Views Asked by At

I have a chat widget which only shows after 4 pm until 9 am (16:00 - 09:00). The widget is being called in wp_footer via <script> tag with external src=.

I want to make sure this script is only loading during the specified hours of the day: 16:00 - 09:00 (next day), where it actually shows. When the widget doesn't show, there is no need to load the script.

I have managed to make this work using strtotime function and relative formats, from this thread.

function custom_script_loader_footer() {
  // Load only between 9:00 and 17:00.
  if ( time() < strtotime( '09:00AM' ) && time() > strtotime( '04:00PM' ) ) {
    ?>
    <script src="https://the-link-here" async></script>
    <?php 
  }
} 
add_action('wp_footer', 'custom_script_loader_footer');

Above solution works, and the script is not loading between those hours.

My question is whether this is a correct way to do what I want to achieve? Is it better to set this up as a cron job when it's a script, as written here?

Any feedback would be appreciated.

1

There are 1 best solutions below

0
Vimal Usadadiya On

You can try it some other way. Below is one of the way, kindly try it.

$hour = date('G');

function custom_script_loader_footer() {
  if ($hour >= 9 && $hour <= 16) {
    ?>
    <script src="https://the-link-here" async></script>
    <?php 
  }
} 
add_action('wp_footer', 'custom_script_loader_footer');