0

I'm really newbie in Wordpress development (around 24 hours ago). I'm trying to build a custom plugin that detects the hour of the user depending on their time zone (not time zone of the Wordpress site) to achieve that, I'm making a shortcode that executes a short Javascript code (in this JS I get the local time of the client side) the result of this JS script I need to get it in the function that executes the shortcode. I have this:

PHP

function range_hour($atts, $content = null){

    wp_register_script( 'custom-script', plugins_url( 'assets/js/timezone.js', __FILE__ ), array( 'jquery' ) );
    wp_enqueue_script( 'custom-script' );
    $tz = 'America/Bogota';
    $timestamp = time();
    $dt = new DateTime("now", new DateTimeZone($tz));
    $dt->setTimestamp($timestamp);
    $hour = $dt->format('G');
}

Javascript

Intl.DateTimeFormat().resolvedOptions().timeZone

As you can see in the JS code I'm getting the timezone of the client, until here all fine, but in the PHP code I need to get this result, to replace "America/Bogota" for the JS result. Any ideas how can I achieve this? I'm thinking to make an endpoint, pass the data from JS to that endpoint, but again... How can I get this result in the shortcode function?

Thanks in advanced.

  • if you just want to display the local hour, you can do it with JavaScript developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/… – mmm Apr 13 '18 at 16:41
  • @mmm Hi, thanks for your reply. But that's not I need. I need to pass the local time (or any object) to the shortcode function. – dfrojas Apr 13 '18 at 19:45
  • It's probably better to describe in detail the problem you are trying to solve rather than ask how to implement what you think is the solution. Shortcodes run server-side, javascript runs on the client side after the request that renders the shortcode has completed. – Milo Apr 13 '18 at 23:25
  • Not possible in a single request. Once the page is loaded, PHP functions won't be executed. you can use an ajax request to send back the JS result to your server. – Jack Johansson Apr 14 '18 at 18:13

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.