diff --git a/blog.config.js b/blog.config.js index 0b62db37..312d4603 100644 --- a/blog.config.js +++ b/blog.config.js @@ -26,6 +26,7 @@ const BLOG = { POST_LIST_STYLE: 'page', // ['page','scroll] 文章列表样式:页码分页、单页滚动加载 POST_LIST_PREVIEW: process.env.NEXT_PUBLIC_POST_PREVIEW || 'false', // 是否在列表加载文章预览 POST_PREVIEW_LINES: 12, // 预览博客行数 + POST_RECOMMEND_COUNT: 6, // 推荐文章数量 POSTS_PER_PAGE: 6, // post counts per page POSTS_SORT_BY: 'notion', // 排序方式 'date'按时间,'notion'由notion控制 diff --git a/pages/article/[slug].js b/pages/article/[slug].js index 9eb1bd65..e3f71f51 100644 --- a/pages/article/[slug].js +++ b/pages/article/[slug].js @@ -51,7 +51,7 @@ export async function getStaticProps ({ params: { slug } }) { const prev = allPosts.slice(index - 1, index)[0] ?? allPosts.slice(-1)[0] const next = allPosts.slice(index + 1, index + 2)[0] ?? allPosts[0] - const recommendPosts = getRecommendPost(post, allPosts) + const recommendPosts = getRecommendPost(post, allPosts, BLOG.POST_RECOMMEND_COUNT) return { props: { @@ -76,25 +76,32 @@ export async function getStaticProps ({ params: { slug } }) { * @param {*} count * @returns */ -function getRecommendPost (post, allPosts, count = 5) { - let filteredPosts = [] - for (const i in allPosts) { +function getRecommendPost (post, allPosts, count = 6) { + let recommendPosts = [] + const postIds = [] + const currentTags = post.tags + for (let i = 0; i < allPosts.length; i++) { const p = allPosts[i] - filteredPosts.push(Object.assign(p)) + if (p.id === post.id || p.type.indexOf('Post') < 0) { + continue + } + + for (let j = 0; j < currentTags.length; j++) { + const t = currentTags[j] + if (postIds.indexOf(p.id) > -1) { + continue + } + if (p.tags && p.tags.indexOf(t) > -1) { + recommendPosts.push(p) + postIds.push(p.id) + } + } } - if (post.tags && post.tags.length) { - const currentTag = post.tags[0] - filteredPosts = filteredPosts.filter( - p => p && p.slug !== post.slug && p.tags && p.tags?.includes(currentTag) && p.type === ['Post'] - ) + if (recommendPosts.length > count) { + recommendPosts = recommendPosts.slice(0, count) } - - // 筛选前5个 - if (filteredPosts.length > count) { - filteredPosts = filteredPosts.slice(0, count) - } - return filteredPosts + return recommendPosts } export default Slug