I have an post article, with a title date and the category the post is assigned to. The post is in multiple categories, but i only want to show the 'main' one its in and none of the others (for now).

How do i search through all the categories the post is assigned to and only show the one with the most posts in? Therefore giving that category the idea as the main one?

I assume cycling through get_the_category counting all the posts within all the categories assigned to this post and then picking the one with the most?

$category_main = get_the_category(); //But only the one with the more posts than the others?

if ( ! empty( $category_main ) ) {
    echo '<a href="' . esc_url( get_category_link( $category_main[0]->term_id ) ) . '">' . esc_html( $category_main[0]->name ) . '</a>';

Thank you for any ideas :)

1 Answer 1


get_the_category() returns an array of WP_Term objects, so you already have access to the count property - just sort the array by it and retrieve the one with the highest count:

$main_category = current( wp_list_sort( get_the_category(), [ 'count' => 'DESC' ] ) );

Check out the documentation for wp_list_sort()

  • Perfect thank you :)
    – user4630
    Commented Jul 4, 2022 at 10:31

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.