skip to Main Content

I know I’ll get hate for this but for the life of me, I cannot figure out why nothing shows when there’s no post to show in a category!
I’m trying to show the user No items to show when there’s no post in a specific category menu with the code below but it’s not showing anything and there’s no error.

<?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: The code works and shows the posts when there’s 1 or more post to show.

2

Answers


  1. The function __() doesn’t echo, it returns. You need to either echo the result, or use the echoing variant _e()

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

    or

    <p><?php _e('No items to show'); ?></p>
    
    Login or Signup to reply.
  2. It seems like you are missing the echo statement in your else block for displaying the "No items to show" message. Also, you need to use esc_html__ to properly handle translations and output escaping. Here’s the corrected code:

    <?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>
    

    Make sure to replace ‘your-text-domain’ with the actual text domain used in your theme or plugin for localization. Also, confirm that your translation files are set up correctly. The esc_html__ function is used to translate and escape the text for safe output.

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search