Ordering articles by views in deskStructure.js for Sanity.io

2 replies
Last updated: Jun 7, 2024
How do i order the childs in my deskStructure.js? I want them to order my articles by views.Been searching for so long now. anyone has an idea_

.child(
S.documentTypeList('article')
.title('Artikler efter sidevisninger')
.filter('_type == "article"')
.ordering({
title: 'Views Descending',
by: [
{field: 'views', direction: 'desc'}
]
})
),
AI Update

Your code is almost correct! The method you're looking for is defaultOrdering() instead of ordering(). Here's the fix:

.child(
  S.documentTypeList('article')
    .title('Artikler efter sidevisninger')
    .filter('_type == "article"')
    .defaultOrdering([
      {field: 'views', direction: 'desc'}
    ])
)

The key differences from your code:

  • Use defaultOrdering() instead of ordering()
  • Pass the ordering array directly as an argument (not wrapped in an object with by and title properties)
  • The array contains objects with field and direction properties

So the correct pattern is:

.defaultOrdering([
  {field: 'fieldName', direction: 'desc'} // or 'asc'
])

You can also specify multiple ordering criteria if needed:

.defaultOrdering([
  {field: 'views', direction: 'desc'},
  {field: 'title', direction: 'asc'}
])

This will order your articles by views in descending order (highest views first) in your desk structure. The defaultOrdering() method is part of the Structure Builder API and works with both S.documentTypeList() and S.documentList().

One gotcha to be aware of: If you select a custom sort order manually in the Studio UI, it will override your defaultOrdering configuration and save that preference to local storage. If your configuration doesn't seem to be working, try clearing your browser's local storage or testing in a different browser.

πŸ‘‹ Do you have a
views
field defined in your schema?
Yes i have - I ended up with another solution by putting it in to an orderlist instead tho πŸ™‚orderings: [
{
title: '| Fleste visninger',
name: 'viewsDesc',
by: [
{field: 'views', direction: 'desc'}
]
},
],

Sanity – Build the way you think, not the way your CMS thinks

Sanity is the developer-first content operating system that gives you complete control. Schema-as-code, GROQ queries, and real-time APIs mean no more workarounds or waiting for deployments. Free to start, scale as you grow.

Was this answer helpful?