如果 WordPress 类别中没有可显示的帖子,则显示默认文本

问题描述 投票:0回答:2

我知道我会因此而讨厌,但对于我的一生,我无法弄清楚为什么当类别中没有可显示的帖子时什么也没有显示! 当特定类别菜单中没有带有以下代码的帖子时,我试图向用户显示

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 个或多个帖子要显示时,代码可以正常工作并显示帖子。

php wordpress wordpress-theming
2个回答
0
投票

函数

__()
不会
echo
,它会返回。您需要
echo
结果,或使用回显变体
_e()

<p><?php echo __('No items to show'); ?></p>

<p><?php _e('No items to show'); ?></p>

0
投票

您似乎在 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__ 函数用于翻译和转义文本以安全输出。

© www.soinside.com 2019 - 2024. All rights reserved.