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:
where
Argument:- The
orderby
parameter determines the field by which categories are sorted.COUNT
is used to sort by thecount
field. - The
order
parameter sets the sorting direction:DESC
(Descending): Highest count first.ASC
(Ascending): Lowest count first.
- The
- 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.