Load the Latest Posts by Category via WordPress Menu using jQuery load


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.

WordPress Ajax Submenu

We wanted to do the same here on Martech Zone. 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.

NOTE: One aspect of their method that I don't believe is a good solution is passing the entire query_post string via JavaScript… it seems to me that you're opening up yourself for a hacking! I've modified the script for this site so that I only pass the parameters necessary within the query_posts command.

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.

So… thanks to the collaborative efforts of 3 WordPress sites and some fine-tuning by our jQuery guru at DK New Media, Stephen Coley (for smoothing the menu out), we have a very nice submenu system!

All of the work was accomplished within our theme files. We loaded the navigation menu filters in functions.php, added the submenu div to our theme's header.php file, added a submenu template to our them, and load a submenu JavaScript file in our header – ensuring that jQuery is already loaded in our theme as well. Hope you appreciate the work, it was a fun update to the site!


  1. 1
  2. 6
  3. 8

What do you think?

This site uses Akismet to reduce spam. Learn how your comment data is processed.