How to Order Categories by Most Recently Updated in WordPress

Home » Snippets » How to Order Categories by Most Recently Updated in WordPress
0

Created with:

Visibility: 

public

Creator: WPTurbo Team

Customize with WPTurbo AI
X

Add Snippet To Project

New Project
Add To Existing Project

Managing and prioritizing categories on your WordPress site can be a daunting task, especially when you have a plethora of posts under each one. What if you want to order your categories by those that are most recently updated? It can definitely be a game-changer, enabling your visitors to always see the freshest content first. In this article, we will guide you step by step on how to reorder your categories based on recent updates.

					function wpturbo_order_categories_by_updated() {
    $categories = get_categories(array(
        'orderby' => 'modified',
    ));
}
add_action( 'pre_get_posts', 'wpturbo_order_categories_by_updated' );
				

In this code snippet, we are creating a function called wpturbo_order_categories_by_updated(). This function is going to modify the way we retrieve categories in WordPress, ordering them by the most recently updated.

Let’s break it down:

The function wpturbo_order_categories_by_updated() is called. Inside this function, we are calling the get_categories() function, which is a WordPress function used to fetch all categories.

function wpturbo_order_categories_by_updated() {
    $categories = get_categories(array(
        'orderby' => 'modified',
    ));
}

get_categories() accepts an optional array parameter where you can specify what categories to retrieve and how to order them.

In our case, we are passing an array with one element, 'orderby' => 'modified'. The orderby key controls how the categories are ordered. The value "modified" means that the categories should be ordered by their last modified date, with the most recently updated categories appearing first.

Finally, we hook our function into the ‘pre_get_posts’ WordPress action using add_action(). add_action() allows us to specify when our function should run.

add_action( 'pre_get_posts', 'wpturbo_order_categories_by_updated' );

In this case, ‘pre_get_posts’ means that our function will run before WordPress gets the posts for a particular query. Because we are modifying the ‘orderby’ property, our function needs to run before WordPress performs the query, otherwise it won’t have any effect.

To sum it up, this code snippet retrieves all WordPress categories and sorts them by their last modified date. The function wpturbo_order_categories_by_updated() is hooked into the ‘pre_get_posts’ action, so it runs just before WordPress performs its query to get posts. As a result, the categories are sorted by their last modified date, with the most recently updated categories appearing first.

Register an account to save your snippets or go Pro to get more features.