Sort Categories by Count in WPGraphQL

To sort WordPress categories by the count field (e.g., the number of posts in each category) using WPGraphQL, you can use the orderby argument with the value COUNT.

Here’s how you can modify your query:

query GetCategories {
  categories(where: {orderby: COUNT, order: DESC}) {
    nodes {
      id
      databaseId
      name
      slug
      count
    }
  }
}

Explanation:

  1. where Argument:
    • The orderby parameter determines the field by which categories are sorted. COUNT is used to sort by the count field.
    • The order parameter sets the sorting direction:
      • DESC (Descending): Highest count first.
      • ASC (Ascending): Lowest count first.
  2. Fields:
    • id: GraphQL unique identifier.
    • databaseId: WordPress database ID for the category.
    • name: The category name.
    • slug: The URL-friendly version of the category name.
    • count: The number of posts associated with the category.

Expected Output:

The query will return categories sorted by their post count in descending order, with the highest count first. If order: ASC is specified, it will return categories sorted in ascending order.

Author: Danyal
I'm a skilled programmer specializing in Vue.js/Nuxt.js for front-end development and PHP Laravel for back-end solutions. I have a strong focus on API design and development, complemented by experience in web server setup and maintenance. My versatile expertise ensures seamless creation and maintenance of web applications, covering everything from intuitive user interfaces to robust server-side functionality. Passionate about coding and driven by a lifelong learning mindset, I invite you to explore more at danyal.dk.