Skip to main content

Load an AJAX PHP file from WordPress

On my website, I have a caching plugin called WP Rocket, which is an awesome plugin, but one downside is that if you have dynamically generated content, it will be cached.
For example, on my website, I have a cool PHP widget that figures out the current time, and then displays a message based on the time. With caching, that plugin will no longer be dynamic because it will just show the result from the time that it was cached.

To overcome this, I needed to create a separate PHP file, place it into my WordPress theme and then load it via Jquery AJAX so that it is loaded every time even if the page is cached.

To do this, firstly, you need to create a div container in your site where you’d like the php to load.
Eg.




<div id="#mycontainer"></div>



Then, in the footer.php template of your theme, underneath the WordPress get_footer php line, type this:

<script>
$(document).ready(function(){ 
$('#mycontainer').load('<?php echo get_template_directory_uri(); ?>/my-php-file.php');

});
</script>

Obviously change the container and “my-php-file.php” to your PHP file name.

Now, when the page loads when cached, it will still load that PHP file dynamically and run your functions properly.
Hope that helps!

Leave a Reply