避免在3个WordPress循环中重复发布的解决方法可以使用一个数组来跟踪已经发布过的文章,以便在后续的循环中进行检查。以下是一个示例代码:
// 创建一个空数组来存储已发布过的文章ID
$published_posts = array();
// 第一个循环
$loop1 = new WP_Query( array( 'post_type' => 'post', 'posts_per_page' => 5 ) );
if ( $loop1->have_posts() ) {
while ( $loop1->have_posts() ) {
$loop1->the_post();
// 检查文章ID是否已经发布过,如果是,跳过该文章
if ( in_array( get_the_ID(), $published_posts ) ) {
continue;
}
// 发布文章
// ...
// 将已发布文章ID添加到数组中
$published_posts[] = get_the_ID();
}
}
// 第二个循环
$loop2 = new WP_Query( array( 'post_type' => 'post', 'posts_per_page' => 5 ) );
if ( $loop2->have_posts() ) {
while ( $loop2->have_posts() ) {
$loop2->the_post();
// 检查文章ID是否已经发布过,如果是,跳过该文章
if ( in_array( get_the_ID(), $published_posts ) ) {
continue;
}
// 发布文章
// ...
// 将已发布文章ID添加到数组中
$published_posts[] = get_the_ID();
}
}
// 第三个循环
$loop3 = new WP_Query( array( 'post_type' => 'post', 'posts_per_page' => 5 ) );
if ( $loop3->have_posts() ) {
while ( $loop3->have_posts() ) {
$loop3->the_post();
// 检查文章ID是否已经发布过,如果是,跳过该文章
if ( in_array( get_the_ID(), $published_posts ) ) {
continue;
}
// 发布文章
// ...
// 将已发布文章ID添加到数组中
$published_posts[] = get_the_ID();
}
}
// 重置查询
wp_reset_postdata();
在上面的代码中,我们使用一个名为$published_posts
的数组来跟踪已经发布过的文章ID。在每个循环中,我们使用in_array()
函数来检查文章ID是否已经存在于数组中,如果是,则跳过该文章。在发布文章后,我们将文章ID添加到数组中,以便在后续的循环中进行检查。
最后,我们使用wp_reset_postdata()
函数来重置WordPress查询,以防在代码中的后续部分使用其他查询。这样可以确保代码的正常运行,并避免与其他查询发生冲突。