Loading Frontend AJAX Content in WordPress
If you want to load some content on demand without a page refresh WordPress has you covered. AJAX is employed in the admin area and we can use those built in functions to achieve the same at the frontend.
The following code is available on github:gist.
Firstly we need to get the ajax functionality loaded on the frontend. The
function fronted_ajaxurl()
below loads the file into our document head.
The PHP
Then we declare what we want to load and create function to load that content. Note that at the end of
function dhf_loadme_ajax()
we call
die();
. This is to make sure the action ends, otherwise you end up in a kerfuffle. You’ll need to put the
fronted_ajaxurl
in your functions.php file, and the content you want to call can go anywhere as long as it’s linked to somehow. Keep it in your functions.php file if you’re unsure.
Note also there are two
add_action()
calls. One is for users who are logged in, one is for users not logged in. See codex.wordpress.org/AJAX_in_Plugins
The JavaScript
JavaScript makes it all work:
I’m using jQuery here to call the function we declared up there in the PHP.
To make the whole process more fluid looking I’ve replace my “button” with an AJAX loading image while the content we actually want it being fetched.
The Sundries
There’s some code there for a button, and don’t forget some CSS to put the AJAX loading image in place.
And…
It’s all actually quite straight forward to do this. And by being a bit more creative with the JavaScript you could choose to load instantly content viewed on the desktop, and for mobile devices load it if the user requests it. That could be part of your Responsive Web Design plan. Go forth.