Over a year ago, Jeremy Keith wrote an excellent post on enhancing the performance of responsive sites by checking for a minimum screen width before loading secondary content such as related news and latest tweets. Mobile devices would just show a link to the content, thus keeping it accessible. In this post I’ll show how to do a similar thing in WordPress.
Method 1: Custom page templates
I thought there should be an easy way to delay the loading of any secondary content, and my first thought was to use the very simple
.load() method in jQuery along with a custom page. For instance you could create a special template to show related blog posts, and display a link to that page. On wide screens this link can be replaced with the content of your custom page using ajax. This is a perfectly valid way of doing it, especially if you have only one or two pieces of secondary content.
Method 2: Custom Endpoints
What if I want to conditionally load the WordPress sidebar on every page, and the contents of the sidebar is not necessarily the same everywhere? Creating page templates and pages for all that secondary content can become messy and error-prone. My esteemed colleague (and boss) Aki suggested a better way of doing this would be to check for a specific parameter in PHP and generate either the main content or the sidebar. All we need is the sidebar version of the page to have its own URL. Enter
Sandman WordPress Endpoints!
URL endpoints are part of the Rewrite API, and are used for many things, among others to generate feeds (via
/feed/) and paging (eg.
/page/2/ to see older posts or the second part of split post). The following code will register a new endpoint
The above code should go in the theme functions.php file, or better yet, a separate plugin. To make the endpoint actually work you might have to clear your rewrite rules — simply opening the WordPress Permalinks settings and saving should do the trick.
Now the endpoint is registered, you can access it in PHP using the built-in WordPress function
get_query_var(). For example, you could construct your
sidebar.php template like this:
In the above example, when we access a URL ending /part/sidebar/, the condition will evaluate to true. So now we have an accessible, functional solution with cacheable URL’s. We’ll just add some jQuery magic to load the sidebar content in place on wider screens:
If you also want to support ajax loading on smartphones, add this to trigger it with a tap/click:
That’s all! A functioning demo can be seen on this blog: try loading it on a small screen vs. a wide screen.