如何让Contentful博客文章按创建日期而非更新日期排序?
问题描述
我使用Contentful管理自建网站的博客文章,已完成内容模型配置且文章能在页面正常展示,但更新旧文章后,该文章会移至页面顶部——当前文章是按最近更新时间排序,而非创建日期。请问是否可以在Contentful后台修改文章的排序方式?还是必须通过代码实现?
附获取文章的代码:
const getPosts = async () => { try { const response = await client.getEntries({ content_type: "contentType", }); const posts = response.items.map((content) => { const title = content.fields.postTitle; const post = content.fields.postContent.content; const date = content.fields.date; const headerImagesObject = content.fields.photoSlideshow; const id = content.sys.id; const imageFileArray = []; headerImagesObject.forEach(function (image) { const file = image.fields.file.url; imageFileArray.push(file); }); return { title, date, post, imageFileArray, id }; }); setPosts(posts); setLoading(false); } catch (error) { setLoading(false); console.log(error); } };
页面渲染代码:
<div> {posts.map((content) => { const { title, date, post, imageFileArray, id } = content; return ( <article key={id} className="mb-24 mx-6 xl:mx-64 lg:mx-32 bg-blog-bg px-12 py-12 rounded" > <div className="xl:flex xl:flex-col xl:items-center"> <Splide className="slideshow-container" options={{ gap: "1rem", type: "loop", width: "50vw", autoplay: true, pagination: false, speed: 3000, interval: 4000, pauseOnHover: true, pauseOnFocus: true, }} > {imageFileArray.map((image) => { return ( <SplideSlide key={image}> <div> <img src={image} alt="image" /> </div> </SplideSlide> ); })} </Splide> <div className="flex justify-between items-center my-6 flex-col"> <h3 className="text-4xl font-bold">{title}</h3> <h5>{date}</h5> </div> <div className="post-container"> {post.map((content) => { let nodeType = content.nodeType; if (nodeType == "embedded-asset-block") { let bodyImage = content.data.target.fields.file.url; let imageDesc = content.data.target.fields.title; return ( <img src={bodyImage} alt={imageDesc} key={imageDesc} className="h-64 m-4 rounded" /> ); } if (nodeType == "paragraph") { let pContent = content.content[0].value; if (pContent == "") { return <hr key={pContent} className="opacity-0"></hr>; } else { return <p key={pContent}>{pContent}</p>; } } if (/^heading-[1-8]$/.test(nodeType)) { let nodeTypeArray = Array.from(nodeType); let headerType = nodeTypeArray[nodeTypeArray.length - 1]; let headerValue = content.content[0].value; let headerClasses = `text-2xl`; if (headerType === "1") { headerClasses = `text-4xl font-bold my-4`; } else if (headerType === "2") { headerClasses = `text-3xl font-semibold my-4`; } else if (headerType === "3") { headerClasses = `text-2xl font-semibold my-4`; } else if (headerType === "4") { headerClasses = `text-1xl font-semibold my-4`; } else if (headerType === "5") { headerClasses = `text-xl font-semibold my-4`; } return React.createElement( `h${headerType}`, { key: headerValue, className: headerClasses }, headerValue ); } })} </div> </div> </article> ); })} </div>
解答
关于排序方式的修改途径
Contentful后台无法直接修改文章的默认排序逻辑,必须通过代码实现排序控制。
为什么默认按更新时间排序?
Contentful的getEntries接口默认是按sys.updatedAt(最近更新时间)降序返回数据,所以更新旧文章后,它会被推到列表顶部。
两种实现按创建日期/自定义发布日期排序的方法
方法1:API请求时指定排序(推荐)
直接在getEntries的参数中添加order字段,指定按自定义发布日期或系统创建时间排序,让Contentful返回已经排好序的数据,效率更高。
修改你的请求代码:
const response = await client.getEntries({ content_type: "contentType", // 按自定义的date字段降序(最新发布的在前) order: "-fields.date" // 若想用系统创建时间,替换为:order: "-sys.createdAt" });
注意:如果用自定义
date字段,要确保该字段在Contentful内容模型中是日期类型,且所有文章都正确设置了该值。sys.createdAt是Contentful自动生成的创建时间,无需额外配置。
方法2:前端获取数据后排序
如果不想修改API请求,可在获取并映射数据后,用sort方法对数组排序:
const posts = response.items.map((content) => { // 原map逻辑不变 const title = content.fields.postTitle; const post = content.fields.postContent.content; const date = content.fields.date; const headerImagesObject = content.fields.photoSlideshow; const id = content.sys.id; const imageFileArray = []; headerImagesObject.forEach(function (image) { const file = image.fields.file.url; imageFileArray.push(file); }); return { title, date, post, imageFileArray, id }; // 按date字段降序排序 }).sort((a, b) => new Date(b.date) - new Date(a.date));
若用系统创建时间,将
date替换为content.sys.createdAt,并在返回的对象中加入该字段。
内容的提问来源于stack exchange,提问作者user22586475
相关产品推荐
相关产品推荐

