- 24 March 2019
- WordPress (25)
This can be achieved using WordPress shortcodes.
A shortcode is a WordPress-specific code that lets you do nifty things with very little effort. Shortcodes can embed files or create objects that would normally require lots of complicated, ugly code in just one line. Shortcode = shortcut.
WordPress.com
By default you can’t add shortcodes to menu items, so firstly, let’s allow them! Add this code to your functions file:
//allow shortcodes in menu items add_filter('wp_nav_menu_items', 'do_shortcode');
Now, let’s create a function that returns a variable for us to display. You could return pretty much anything you like but in this example we’ll count one of our categories by it’s ID number (ID 3 in this example), return that total, then add a shortcode hook:
function count_category() { $category = get_category(3); $count = $category->category_count; return $count; } add_shortcode('count-category', 'count_category');
We now have a shortcut that we can use on our theme: [[count-category]], which runs our ‘count_category’ function, which returns a value.
Ok, we’re pretty much there now. All that’s left to do is add our shortcode to a menu item. Create a new menu item and change its label to:
And there you have it! You could extend this further by creating a reusable function that uses passed parameters to count different categories.
The full code:
//allow shortcodes in menu items add_filter('wp_nav_menu_items', 'do_shortcode'); function count_category() { $category = get_category(3); $count = $category->category_count; return $count; } add_shortcode('count-category', 'count_category');
Let us know how you’ve used this idea in your theme(s) via the comments below.
Comments
Whether you have feedback, a question, want to share your opinion, or simply want to say thank you - we welcome comments! Please read the disclaimer.