In a couple of recent projects, I’ve been tasked with adding tabbed navigation to various WordPress templates. The thing is, these tabs work in such a way that all of the information is loaded on the page so when the user clicks on the tab, the contents of the page appear without having to do a page refresh.
In some cases, it may be best to load pages via Ajax, in some cases, it’s better to load things up all in the first page load. This particular post is about the best strategies for that (that’s a debate for another post).
Tabbed Navigation in a Single Template
In this post, I’m assuming that you have an area on your page in which the tabbed navigation exists and the content for each page is loaded when the parent page is loaded.
For the sake of this example, let’s say that you have a container in which the tabs and the page content are contained. Let’s also say that we only want to display the container if there are tabs as part of the navigation.
To do this, we need several functions:
- A function to check for the existence of menu items
- A function for retrieving posts that correspond to the menu items
- A way to render the tabs
- A way to render the tabbed content
Yes, all of this could be contained inline of a template but that doesn’t separate the concerns and it makes the code harder to read. And yes, all of this could technically go into a single function, but that would give that function too much responsibility, and the template calling the function wouldn’t be as easy to read.
For this example, assume that I have a menu locations called “Pages” and that I’m only concerned with pulling page
page post types. So with that said, here’s a breakdown of how your functions may look (there’s obviously going to be some variation depending on your needs).
First, we need a function to determine if the “Pages” menu has menu items that are set in the backend:
Then, we need a function to retrieve the post IDs that are contained within the “Pages” menu. These IDs will later be used to pull the title, content, and any other meta data you may want associated with the post.
After that, we need to render the actual navigation tabs. I’m using a
dl element, but this can obviously be done using whatever element you find most useful.
Finally, we need to render the tabbed content. In this particular example, I’m using some classes that correspond to Foundation (as that’s the front-end framework I was using), but this would obviously be a bit different depending on what you’re using.
Then, with the functions we’ve defined, you can write something like this in the page template:
Again, your actual implementation of this may differ – and likely will – but the general idea still remains the same.
Remember to keep each function as lean as possible, and remember to make sure that they’re named in such a way that not only follows the WordPress coding standards, but also reads well within the context of the template that’s calling into them.