Skip to content
View in the app

A better way to browse. Learn more.

Web Designer Forum

A full-screen app on your home screen with push notifications, badges and more.

To install this app on iOS and iPadOS
  1. Tap the Share icon in Safari
  2. Scroll the menu and tap Add to Home Screen.
  3. Tap Add in the top-right corner.
To install this app on Android
  1. Tap the 3-dot menu (⋮) in the top-right corner of the browser.
  2. Tap Add to Home screen or Install app.
  3. Confirm by tapping Install.

Sort WordPress categories by ID?

Featured Replies

Hi All,

 

So I have some custom PHP in WordPress that loops through a custom taxonomy, showing the title of the taxonomy and then its associated posts below it.

 

My code looks like this:

<?php
// get all the categories from the 'press_cat' custom taxonomy
$cats = get_terms('press_cat');
 // loop through the categories
 foreach ($cats as $cat) {
	 // setup the category ID
	 $cat_id = $cat->term_id;
	 // Make a header for the cateogry
	 echo "<h2>".$cat->name."</h2>";
	 // create a custom wordpress query
	 query_posts(array('post_type' => 'press','cat' => $cat->cat_id, 'press_cat' => $cat->name, 'orderby' => 'id'));
	 // start the wordpress loop
	 if (have_posts()) : while (have_posts()) : the_post(); ?>

		 <?php print_post_title() ?><br />
	 <?php endwhile; endif; } ?>

 

This is great and works well however, it's listing the categories in alphabetical order. I'd like to order them from newest to oldest (top to bottom) but as WordPress doesn't store creation dates for categories in the database, i've read that sorting them by their ID should produce the same effect.

 

As the above code is fairly custom, Its not quite as simple as using wp_list_categories.

 

Can someone offer any help on how I can add my requested feature to the above code?

 

Many thanks for any help, advice or suggestions in advance.

Jack

Edited by jackmcconnell

$cats = get_terms('press_cat',
 array(
   'orderby' => 'id',
   'order' => 'DESC'
 ));

 

Would it hurt too much to RTFM?

Edited by Renaissance-Design

  • Author

Thanks. That works great.

 

That's a little harsh-a-comment. If you read my footer, I always try and work this out myself and then resort to posting here.

Next time, i'll mention that I read the Codex, Googled it and tried to work it out for over an hour!

Create an account or sign in to comment

Account

Navigation

Search

Search

Configure browser push notifications

Chrome (Android)
  1. Tap the lock icon next to the address bar.
  2. Tap Permissions → Notifications.
  3. Adjust your preference.
Chrome (Desktop)
  1. Click the padlock icon in the address bar.
  2. Select Site settings.
  3. Find Notifications and adjust your preference.