我正在使用下面的代码分别显示不同的post类型/分段表单的搜索结果。
if (have_posts()) {
// In the below line of code you can set the loop order in array (1, 2, 3, 4)
// You can also turn a post type off by removing it from the below line.
$types = array('post', 'page', 'sfwd-courses', 'product');
foreach ($types as $type) {
// Here you can customize both the titles, section heading title & side title
if ($type == 'post') {
$head_title = "Results in Posts";
$side_title = "post";
}
if ($type == 'page') {
$head_title = "Results in Pages";
$side_title = "page";
}
if ($type == 'sfwd-courses') {
$head_title = "Results in Courses";
$side_title = "course";
}
if ($type == 'product') {
$head_title = "Results in Products";
$side_title = "product";
}
// This div below shows up the head title for each section
echo '<div class="search-section"><h4>' . $head_title . '</h4></div>';
while (have_posts()) {
the_post();
if ($type == get_post_type()) {
?>
<article id="post-<?php the_ID(); ?>" <?php post_class(''); ?> role="article">
<header class="article-header">
<div class="article-header-content">
<h3 class="title head-2"><a href="<?php the_permalink() ?>" rel="bookmark" title="<?php the_title_attribute(); ?>"><?php the_title(); ?></a></h3>
<!-- This div below shows up the side title for each section -->
<div class="posttypetext"><i> <?php echo $side_title; ?> </i></div>
</div>
<!-- <?php get_template_part('parts/content', 'byline'); ?> -->
</header> <!-- end article header -->
</article> <!-- end article -->
<?php }
}
rewind_posts();
}
} else {
get_template_part('template-parts/content', 'missing');
}这向我展示了一个搜索结果的列表,首先显示所有的帖子,然后是页面的结果,然后是课程,最后是产品。
现在的分页限制是每页20页。
我希望在每一页上,我应该得到5搜索结果从帖子,5从页面,5课程和5产品。
这是必要的,因为如果有30-40个帖子的结果,它将掩盖前2页的搜索结果,用户将不会看到任何课程或产品,将躺在3,4页。
我希望这是有意义的,有办法做到这一点吗?
谢谢JS
发布于 2022-01-27 20:24:26
有多种方法来设置它。最简单的方法是利用查询的current_post属性,这将为您提供当前post的索引号。
因此,在您的代码中,您可以替换这一行:
if( $type == get_post_type()){
// your template section
}用这一行:
global $wp_query;
if( $type == get_post_type() && $wp_query->current_post <= 4){
// your template section
}它是$wp_query->current_post <= 4,因为current_post是基于零的,您只需要输出前5个帖子!
使用wp_query可以实现同样的目标,但是您还没有提供任何关于如何创建查询的详细信息。您刚刚向我们提供了您的loop模板,我们不知道它是如何被查询的,以及这个循环的位置。所以我认为在这里使用current_post属性是最简单的方式!
https://stackoverflow.com/questions/70884642
复制相似问题