2

I created some custom taxonomies in Wordpress and when I want to show the categories for a custom post type on the frontend, they're listed in alphabetical order.

Is there a code for functions.php that can help me list the Primary Category first, then the other categories?

In the example above, categories show up as "Americas, Europe, Global", but I would like them sorted as "Global, Americas, Europe". The first one should be the primary category, then the others listed in alphabetical order.

Thanks.

1 Answer 1

1

Assuming you are using Yoast SEO plugin - I haven't tested this, but I think you can do something like this: (Source https://pretagteam.com/question/get-primary-category-if-more-than-one-is-selected)


/*
Checks for a yoast primary category, if it exists move the category to the first position in the $categories array.
*/
function yoast_primary_cat_as_first_cat($categories) {

   // Check if yoast exists and get the primary category
   if ($categories && class_exists('WPSEO_Primary_Term')) {

      // Show the post's 'Primary' category, if this Yoast feature is available, & one is set
      $wpseo_primary_term = new WPSEO_Primary_Term('category', get_the_id());
      $wpseo_primary_term = $wpseo_primary_term->get_primary_term();
      $term = get_term($wpseo_primary_term);

      // If no error is returned, get primary yoast term 
      $primary_cat_term_id = (!is_wp_error($term)) ? $term->term_id : null;

      // Loop all categories
      if ($primary_cat_term_id !== null) {
         foreach($categories as $i => $category) {

            /* Move the primary category to the top of the array
    and leave the rest of the categories in the order they were in */

            if ($category->term_id === $primary_cat_term_id) {

               $out = array_splice($categories, $i, 1);
               array_splice($categories, 0, 0, $out);

               break;
            }
         }
      }
   }

   return $categories;
}
add_filter('get_the_categories', 'yoast_primary_cat_as_first_cat');


4
  • Thanks a lot for this. I'm trying to see how I can edit it to work for custom taxonomies. Because I want to reorder categories of a custom post type. Jan 5, 2022 at 13:43
  • I think you can do that by changing new WPSEO_Primary_Term('category', get_the_id()); to new WPSEO_Primary_Term('the-name-of-your-custom-taxonomy', get_the_id()); Jan 6, 2022 at 8:43
  • It's not working for me, unfortunately. I think maybe I should go with a plugin for custom order, although I preferred it like this. Jan 6, 2022 at 10:41
  • @Mr.Fontastic did you finally manage to solve this issue? I have the same requirement and been looking all around for solutions.
    – NJT
    May 15, 2023 at 6:56

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.