When developing a blog- or newslike website/component with Kentico Kontent, you'll probably run into the problem that you can't sort your posts on publish date, since this data is not available in the API.
Luckily, there is a date & time element available in Kontent's model builder, and we have GraphQL built-in in GatsbyJS. So we can use this to sort the data ourselves!
Step 1: Add the date & time element to your content model
Step 2: Add content items
When there are no data available in the API, there's no way you can retrieve the data. So it's wise to add a couple of content items where the Publish date is populated.
If you're planning to publish once in a couple of days, adding the date would suffice. If the plan is to publish multiple articles per day, it's wise to also fill out the time.
Step 3: Add sorting to your GraphQL query
Now we have the publish date available in the API, we can use this to manipulate the items with GraphQL's sorting mechanism.
query ArticleListing {
allKontentItemArticle(sort: {order: DESC, fields: elements___publish_date___value}) {
edges {
node {
id
elements {
title {
value
}
}
}
}
}
}
That's it! When you display the items you'll see that they are sorted on publish date.
For reference, here's how I'm using it on one of my pages in my project:
import React from 'react'
import { graphql } from 'gatsby'
import Layout from '../components/Layout/layout'
import ArticleCard from '../components/Card/article-card'
const articlePage = ({ data }) => {
const articles = data.allKontentItemArticle.edges
return (
<Layout>
{articles.map((article, i) => {
const articleData = article.node.elements
const title = articleData.title.value
const url = articleData.slug.value
const image = articleData.header_image.value[0].url
const alt = articleData.header_image.value[0].description
return <ArticleCard title={title} url={url} image={image} alt={alt} key={i} />
})}
</Layout>
)
}
export const query = graphql`
query ArticleListing {
allKontentItemArticle(
sort: { order: DESC, fields: elements___publish_date___value }
) {
edges {
node {
id
elements {
title {
value
}
header_image {
value {
url
description
}
}
slug {
value
}
}
}
}
}
}
`
export default articlePage
Photo by Icons8 Team on Unsplash
Top comments (0)