我使用rewind_posts()函数根据帖子类型对搜索结果进行分组,并将它们显示在相关选项卡下。循环运行得很好,但我在显示no results found信息时遇到了困难。
例如,如果我正在搜索一个文档,我希望帖子显示在documents下,但是在page和people选项卡下,我需要回显No results。
<?php
if ( have_posts() ) { ?>
<section class="tabs" id="pages">
<?php while( have_posts() ) { the_post(); ?>
<?php if ( $post->post_type == 'page' ) {
include(locate_template('partials/pages.php', false, false)); ?>
<?php } ?>
<?php
} ?>
</section>
<?php
rewind_posts(); ?>
<section class="tabs" id="people">
<?php while( have_posts() ) { the_post(); ?>
<?php if ( $post->post_type == 'people' ) {
include(locate_template('partials/profile.php', false, false)); ?>
<?php } ?>
<?php
} ?>
</section>
<?php
rewind_posts(); ?>
<section class="tabs" id="documents">
<?php while( have_posts() ) { the_post(); ?>
<?php if ( $post->post_type == 'documents' ) {
include(locate_template('partials/document.php', false, false)); ?>
<?php } ?>
<?php
} ?>
</section>
<?php
rewind_posts(); ?>
</div>发布于 2021-11-05 00:51:32
通过使用开关或if/else而不是使用rewind_posts(),看起来您正在做的事情会更有效率
这应该可以在一个循环中工作,尽管我不能实际测试您的代码。
if ( have_posts() ) : ?>
<section class="tabs" id="<?php echo esc_attr( $post->post_type ); ?>">
<?php while ( have_posts() ) {
the_post(); ?>
<?php
// Determine the post type and load the appropriate template
switch ( $post->post_type ) {
case 'page':
default:
include( locate_template( 'partials/pages.php', false, false ) );
break;
case 'people':
include( locate_template( 'partials/profile.php', false, false ) );
break;
case 'documents':
include( locate_template( 'partials/document.php', false, false ) );
break;
}
} // endwhile
?>
</section>
<?php else:
echo 'No Posts Found';
endif;https://stackoverflow.com/questions/69844918
复制相似问题