Dynamic AJAX WordPress Templates
Smaller, cleaner, and easier to manage.

September 1, 2017
posted 3 weeks ago

tagged

I love the Interchange functionality from the Foundation front end framework, but I wanted to create my own take on it so that I could modify it as needed. So I wrote some code to dynamically load with AJAX a partial HTML or PHP template associated with a media query breakpoint. This represents a very first rough draft, but a functional one, and so I thought I would share this as I make incremental improvements until this is a solid utility script in my toolkit.

On the front end side, you set up the element like this:

What we’ve got here is JS object to pass to the script that has a key / value of screen size ‘name’ and the corresponding template file for that size. This allows us to set any number of sizes and files, so once the JavaScript file has been configured, we can then always set this up just as you see above within the display template.

The other item you see is to pass the WordPress post id to the template. Because we are calling it through AJAX, we’re leaving the WordPress ‘ecosystem’ so we’ll need to pass it that much to help with custom fields and other things of that nature. Also you’ll want to make sure your element has an ID because that’s the hook the script is using for the partial template include.

In the swap.js file below, we’re defining our named breakpoints and screen widths so that we have a way to match up what’s there. I did include a provision in case there are only two template sizes (which is common enough – the small and large views). If the current screen size does not match an available template file, it will select the next template it can in the order listed. This means that the JS object created as a data attribute in the front end side above needs to be set in order of smallest to largest. Generally that is the way most people would set it up. If you want to add your files from largest to smallest, this will not work as you want and will have to modify the code to reverse that call.

I wrapped the functionality in a debounce so that the function will only fire after the resize event is over instead of triggering repeatedly. It might introduce a slight delay, but I think this is preferred from a performance standpoint.

On your partial WordPress templates, you’ll want to include this at the head of it to help tie it together with WordPress, since it is essentially being called from outside of it:


require($_SERVER['DOCUMENT_ROOT'].'/wp-load.php');