我正在构建一个古腾堡块,它将帖子分组并以 2 或 3 组的形式显示它们,在两种配置之间交替。这是我想出的代码(为了简洁省略了一些代码):
const { posts, hasPostsResolved } = useSelect(select => {
const query = {
order: 'asc',
orderby: 'title',
status: 'publish',
per_page: 10,
};
return {
posts: select('core').getEntityRecords('postType', 'post', query),
hasPostsResolved: select('core').hasFinishedResolution('getEntityRecords', ['postType', 'post', query]),
}
}, []);
const displayPosts = (posts) => {
var posts_per_slide = 3;
return (
<>
{posts.map((post, index) => {
if (index % posts_per_slide === 0) {
posts_per_slide = (posts_per_slide === 3) ? 2 : 3;
return (
<div key={index / posts_per_slide} className={`post-group posts-${posts_per_slide}`}>
{posts.slice(index, index + posts_per_slide).map((groupedPost, groupIndex) => (
<article
id={`post-${groupedPost.id}`}
className="wp-block-posts-carousel__post"
key={index + groupIndex}
>
<div className="wp-block-posts-carousel__post-thumbnail">
<img src="https://placehold.co/1000x700" width="1000" height="700" />
<h2 className="wp-block-posts-carousel__post-title">
{groupedPost.title.rendered
? decodeEntities(groupedPost.title.rendered)
: __('(no title)')}
</h2>
</div>
</article>
))}
</div>
);
}
return null;
})}
</>
);
};
return (
<>
<div {...blockProps}>
{!hasPostsResolved &&
<Spinner />
}
{hasPostsResolved && posts?.length === 0 &&
<p>
{__('No posts found')}
</p>
}
{hasPostsResolved && posts?.length > 0 &&
<>
<div class="wp-block-posts-carousel__posts">
{displayPosts(posts)}
</div>
</>
}
</div>
</>
);
但它没有按预期工作,因为有些帖子在多个帖子组中重复,而且,我需要第一个组包含三个帖子,而不是两个。
如有任何帮助,我们将不胜感激。
我设法通过在渲染帖子之前将帖子分组为 3 和 2 的数组来找到解决方案:
const displayPosts = (posts) => {
// Group posts in sets of three and two alternately.
var groupedPosts = [];
for (let i = 0; i < 8; i += 5) {
groupedPosts.push(posts.slice(i, i + 3));
groupedPosts.push(posts.slice(i + 3, i + 5));
}
return (
<>
{groupedPosts.map((group, index) => (
<div key={index} className={`post-group posts-${group.length}`}>
{group.map((post, subIndex) => (
<article key={subIndex} id={`post-${post.id}`} className="wp-block-jn-post-carousel__post">
<div className="wp-block-jn-post-carousel__post-thumbnail">
<img src="https://placehold.co/1000x700" width="1000" height="700" />
<h2 className="wp-block-jn-post-carousel__post-title">
{post.title.rendered
? decodeEntities(post.title.rendered)
: __('(no title)')}
</h2>
</div>
</article>
))}
</div>
))}
</>
);
};