Contentful logo

Contentful Community

Pagination blog post (Previous - Next)

#1

Hi,

I am creating a blog and on my blog post page, i need to be able to go to the previous and the next blog post.

Is it possible to do that with a special query set up?

Thanks in advance!

0 Likes

#2

Hi Olivier,

Is there any particular order that you’d like to retrieve your items?

This should be possible by using the Delivery API with an ordering parameter on the lines of order=sys.updatedAt or any other property you’d like to use.

https://www.contentful.com/developers/docs/references/content-delivery-api/#/reference/search-parameters/order

That would retrieve all your items in your desired order, but you can also implement the appropriate pagination parameters to go through each of your items with skip and limit.

https://www.contentful.com/developers/docs/references/content-delivery-api/#/introduction/collection-resources-and-pagination

limit will precisely do that to your response: it retrieves a given amount of items.

skip will ignore the given amount of items in your response.

If you’d like to retrieve the first item of that ordered response, you’d simply add limit=1to your query; for your second item, you’d then add limit=1&skip=2.

0 Likes

#3

Hi @gabriel,

I only see one problem with this solution.

If i click on a random blog post in my blog post listing page, how do i know which post is the previous and the next one?

Thanks in advance.

0 Likes

#4

Hi @olivier.castro-perri,

That’s where the order parameter comes in. :slight_smile:

If you don’t set a value for this parameter, the API will indeed randomly retrieve items without a given order.

But, if you set a value for it, the order will remain the same as long as you don’t change the values that are being used to generate that ordered list of items or create additional items.

In that way, an item in a given position (e.g. forth item of your response) will remain there indefinitely.

With this ordered list of items, you can easily know what post is the previous and the subsequent one, by adding a value of 1 to skip.

0 Likes

#5

Hi @gabriel,

I am trying to follow your instructions but I am having difficulties.

Using your approach, what is used to identify the current blog post?

I use the following code to get an individual blog post by slug.

getEntryBySlug(content_type, slug) {
    return client.getEntries({
        'content_type': content_type,
        'fields.slug[in]': slug,
    })
},

But how do I get a previous or next entry to this using createdAt as the order parameter. Because when I query by slug I obviously only get one entry back. It doesn’t seem like there is any easy way to achieve getting the next and previous entries.

I’d appreciate your help.

0 Likes