WP_Query是WordPress中的一个类,用于查询和显示文章、页面和自定义帖子类型等内容。它可以根据特定的参数设置来过滤和排序查询结果。
要实现显示一个随机帖子,然后显示另外三个随机帖子,而不重复第一个帖子,可以使用以下代码:
// 获取一个随机帖子
$random_args = array(
'post_type' => 'post',
'orderby' => 'rand',
'posts_per_page' => 1
);
$random_query = new WP_Query($random_args);
// 显示第一个随机帖子
if ($random_query->have_posts()) {
while ($random_query->have_posts()) {
$random_query->the_post();
// 显示帖子内容
the_title();
the_content();
}
}
// 重置查询
wp_reset_postdata();
// 获取另外三个随机帖子
$other_args = array(
'post_type' => 'post',
'orderby' => 'rand',
'posts_per_page' => 3,
'post__not_in' => array($random_query->posts[0]->ID) // 排除第一个帖子
);
$other_query = new WP_Query($other_args);
// 显示另外三个随机帖子
if ($other_query->have_posts()) {
while ($other_query->have_posts()) {
$other_query->the_post();
// 显示帖子内容
the_title();
the_content();
}
}
// 重置查询
wp_reset_postdata();
这段代码首先使用WP_Query
查询获取一个随机帖子,并显示其标题和内容。然后,通过在第二个查询中使用post__not_in
参数排除第一个帖子的ID,获取另外三个随机帖子,并显示它们的标题和内容。
推荐的腾讯云相关产品:腾讯云服务器(https://cloud.tencent.com/product/cvm)和腾讯云数据库(https://cloud.tencent.com/product/cdb)可以用于支持WordPress网站的部署和数据存储。
领取专属 10元无门槛券
手把手带您无忧上云