If you’ve visited some of the larger blogs out there like Mashable, you may notice that they have a very nice menu system that drops down and provides you visibility into the latest blog posts from each category. To ensure the page doesn’t take forever to load, they load that content utilizing Ajax… and preload it only after the page is fully loaded.
We wanted to do the same here on the Marketing Technology Blog. To provide some insight into the categories that we have, I wanted to show some posts within each. We’re well-versed at WordPress, the WordPress API and jQuery but it wasn’t until I found an article on Fetching Posts by Category using jQuery that we had a nice solution.
The tutorial steps the user through creating a template to dynamically pull in the posts, and then how to build links that can initiate the request. It would have been easy had we wanted to just make some links, but we actually wanted to utilize WordPress’ built in navigation menu. Unfortunately for us, WordPress’ menu links have generated numbers as you add and remove menu items… but they don’t actually have any information on the category you wish to pull and pass in your Ajax call.
To label the menu list items properly, we incorporated the code from WPreso, Add page/post slug class to menu item classes.
Only one problem… it works for the page or post, but didn’t actually work for Category! So we updated the request for the slug with:
$slug = get_cat_slug($id);
And added the function from WPRecipes, WordPress trick: Get category slug using category ID, to pull back the category slug into a data attribute in the navigation menu.