Search code examples
phpajaxwordpresstimeshortcode

Wordpress shortcode conditional loading


I am working a WordPress plugin containing a shortcode. This shortcode, is slow (4 sec to execute), due to external API calls, and I need them here, because they will vary on the user id, watching the page.

Actually, I am in the development/testing stage of my plugin. I am trying to implement a fallback behavior which will skip the long API calls, if a certain time is reached, then using a local logic.

I would like to know, if stopping the execution or conditionally render a shortcode is possible? Using a While loop is not a solution as it will loop at least once.

Additionally, I tried using set_time_limit(); PHP in-built function, but it does not seems to work inside WP environment.

Furthermore, I am trying to achieve this without AJAX, if possible. If not i would like also some guidelines, if you can help me, of course.

If you think I need another solution, for example not using shortcode, please advise me. Lazy loading is could also be a solution as in this thread:

What I am trying to achieve would be to have a asynchronous shortcode, possibly with a loader, looking like the modern JS Web Application.

To monitor the execution time of my shortcode, I have inserted this into my function:

<?php
function my_function() {
  $start = microtime(true);
  // function code here
  $time_taken = microtime(true) - $start;
  wp_die( $time_taken ); // in seconds
}

From this source Thank you, any clues will be useful to me.

UPDATE

Using the clues given by the comments, Ajax was the way to go. Using the wordpress register_script and localize_script I made it work.

Since I call an Api, the data will change most of the time, but I found out that my js file, holding the behavior is being cached and the values are not updated without an Hard Refresh.

How to prevent, the browser, or Wordpress from caching this?

Thanks


Solution

  • Using Ajax is the best way to achieve my problem, like in this post: https://stackoverflow.com/a/13614297/18036486

    Furthermore, to prevent the javascript which trigger the ajax handler to be cached, a random version number must be added to it via wp_register_script() https://developer.wordpress.org/reference/functions/wp_register_script/ , using for example the time().

    <?php
    wp_register_script(
        'myscript',
        MAIN_PLUGIN_DIR .'/scripts.js',
        false,
        time(), //random version number
        true);
    wp_enqueue_script('myscript');
    ?>