So after Creating an AI generated blurb on pageload in WordPress, I had a lovely new blub each time I loaded the page, but this caused the page to load very slowly, as the blub was being generated before the page was shown.
For this we needed JQuery and AJAX. The first step was to write the function that would call the shortcode (in the function.php file):
function handle_delayed_shortcode() {
echo do_shortcode('[bio]');
wp_die();
}
Next, I registered AJAX actcions for both logged-in and anon users:
add_action('wp_ajax_load_bio', 'handle_delayed_shortcode');
add_action('wp_ajax_nopriv_load_bio', 'handle_delayed_shortcode');
Finally, I replaced the shortcode on my site with the following custom HTML. Basically it waits for the page to finish loading, then calls the shortcode and writes the result to the elayed-shortcode-container div.
<div id="delayed-shortcode-container">Loading...</div>
<script>
jQuery(document).ready(function($) {
$.ajax({
url: 'https://el3ktra.net/wp-admin/admin-ajax.php',
type: 'POST',
data: {
action: 'load_bio'
},
success: function(response) {
$('#delayed-shortcode-container').html(response);
}
});
});
</script>
Gotchas
Now one of the first things that I ran into, using the TwentyTwentyFive theme, is that JQuery is not loaded, so I had to add this to the end of my functions.php file:
add_action('wp_enqueue_scripts', function() {
wp_enqueue_script('jquery');
});
This allowed JQuery to load on my page.
I determined that JQuery wasn’t running by adding an alert to the JQuery code.
Leave a Reply