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
The function
__()
doesn’techo
, it returns. You need to eitherecho
the result, or use the echoing variant_e()
or
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:
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.