Get All Menu Items In WordPress

In previous project I had to display a list of categories in a certain order, to get the categories out from WordPress we have a few options we can use the get_categories() function or use the get_terms() function. These will do the same thing as the get_categories() function as it's just a wrapper for the get_terms() function. To use the get_categories() function it's very easy you can just use the following code


<?php $categories = get_categories(); ?> 

The categories variable is now populated with an array of all the categories from your WordPress site. The problem I had is that the client wanted to display these categories in a specific order, you do have order arguments that you can pass into the get_categories() function but none of these will return the order the client wanted. The options you have in returning the categories are:

  • id - Return in order of category ID
  • name - Return in order of the category name
  • slug - Return in order of the category slug
  • count - Return in order of posts assigned to the category
  • term_group - The group of terms

These are fine but it doesn't allow me to display a list of categories that the user can define themselves. In the edit category screen there is nothing to allow the user to change the order of the categories, so by default there is no way to specifically choose the order of the categories.

Using Menus For Custom Lists

One of the best features in WordPress is the menu system it allows you to select a number of pages or custom links or categories to add to the menu. You can even reorder these menu item in any order that you want. We can use the menu system to create a way to make a list of categories in any order the user wants. In WordPress we have the ability to get all these items in the menu in the same order set by the user and display them in the theme. To get a list of menu items in WordPress you can use the function wp_get_nav_menu_items(), this takes two parameters first being the menu ID and second being extra parameters to customise the items.

<?php $items = wp_get_nav_menu_items( $menu, $args ); ?> 

The $items variable is now populated with an array of menu items including the name and URL of the page, this means we can now loop through these items to display the list of categories.


<?php

echo '<ul>';

foreach($items as $item)
{
    echo '<li>'.$item->title.'</li>';
}

echo '</ul>';

?>

UpChecker

Reliable uptime monitoring and instant alerts for any website downtime.

  • Uptime Monitoring
  • Performance Monitoring
  • SSL Certificate Alerts
  • Domain Monitoring
  • DNS Checker
  • XML Sitemap Monitoring