我知道我会因此而讨厌,但对于我的一生,我无法弄清楚为什么当类别中没有可显示的帖子时什么也没有显示! 当特定类别菜单中没有带有以下代码的帖子时,我试图向用户显示
No items to show
,但它没有显示任何内容,也没有错误。
<?php
$the_query = new WP_Query( array(
'category_name' => $category_name,
'orderby' => 'post_date',
'order' => 'DESC',
'post_type' => 'post',
'post_status' => 'publish',
'posts_per_page' => 10,
'ignore_sticky_posts' => true,
));
?>
<div class="category">
<?php if ( $the_query->have_posts() ) : ?>
<?php while ( $the_query->have_posts() ) : $the_query->the_post(); ?>
<div class="category__details">
<a href="<?php the_permalink(); ?>"><h4><?php the_title(); ?></h4></a>
</div>
<?php endwhile; ?>
<?php wp_reset_postdata(); ?>
<?php else : ?>
<p><?php __('No items to show'); ?></p>
<?php endif; ?>
</div>
PS:当有 1 个或多个帖子要显示时,代码可以正常工作并显示帖子。
您似乎在 else 块中缺少用于显示“没有可显示的项目”消息的 echo 语句。此外,您需要使用 esc_html__ 来正确处理翻译和输出转义。这是更正后的代码:
<?php
$the_query = new WP_Query( array(
'category_name' => $category_name,
'orderby' => 'post_date',
'order' => 'DESC',
'post_type' => 'post',
'post_status' => 'publish',
'posts_per_page' => 10,
'ignore_sticky_posts' => true,
));
?>
<div class="category">
<?php if ( $the_query->have_posts() ) : ?>
<?php while ( $the_query->have_posts() ) : $the_query->the_post(); ?>
<div class="category__details">
<a href="<?php the_permalink(); ?>"><h4><?php the_title(); ?></h4></a>
</div>
<?php endwhile; ?>
<?php wp_reset_postdata(); ?>
<?php else : ?>
<p><?php echo esc_html__('No items to show', 'your-text-domain'); ?></p>
<?php endif; ?>
</div>
确保将“your-text-domain”替换为主题或插件中用于本地化的实际文本域。另外,请确认您的翻译文件设置正确。 esc_html__ 函数用于翻译和转义文本以安全输出。