Archived topic
Empty category archive page
5 replies · Started by Julien on July 26, 2022
Dear GeneratePress team,
On the category archive page, I would like to display the title and description without any posts.
The following is an example of a category with assigned posts:
https://34.134.162.158/?cat=3
The category title, description, and post loop are all displayed.
If a category does not have any posts, the title will not appear:
https://34.134.162.158/?cat=4
Is it possible to force the title of the category to be displayed?
Thanks in advance,
Julien
Hi Julien,
By default, if there are no posts in a category, the template part that will be used is called no-results.php.
It’s possible however, you’ll need to use a Child theme.
For one, you can make a copy of no-results.php in your child theme and alter this line: https://github.com/tomusborne/generatepress/blob/master/no-results.php#:~:text=%3Ch1%20class%3D%22entry%2Dtitle%22%3E%3C%3Fphp%20_e(%20%27Nothing%20Found%27%2C%20%27generatepress%27%20)%3B%20%3F%3E%3C/h1%3E
Something like this can work:
<?php
if( is_category() ){ ?>
<h1 class="entry-title"><?php echo get_the_archive_title(); ?></h1>
<?php
} else { ?>
<h1 class="entry-title"><?php _e( 'Nothing Found', 'generatepress' ); ?></h1>
<?php } ?>
Hope this helps!
Hi Fernando,
Thanks for your feedback. I've updated the no-results.php file with your recommended code however I still cannot display the H1 on the empty category (attached is a screenshot of the updated code).
https://drive.google.com/file/d/1yRslUuTVmQ3rMJJIkEX8_egBw6SdnD5J/view?usp=sharing
Does something seem wrong to you?
Thank you in advance,
Julien
Nothing’s wrong. Sorry. That would only work if you’re retrieving the title by default.
I just realized you’re using a Page Hero and a Headline Element to retrieve the title in your template.
What you can do is add this PHP snippet:
function archive_title_func($atts, $content = null) {
ob_start();
do_action('archive_hook');
return ob_get_clean();
}
add_shortcode('add_archive_title', 'archive_title_func');
add_action('archive_hook', function(){
echo '<h1>' . get_the_archive_title() . '</h1>';
}, 10);
Adding PHP reference: https://docs.generatepress.com/article/adding-php/#code-snippets
Then, add a Shortcode Block in your Page Hero - Block Element. And, add this shortcode: [add_archive_title].
This shortcode would retrieve the archive title. You can place the Shortcode Block inside a Container Block, and modify the font in the container Block to modify the font of the title if needed.
Hope this helps!
Hi Fernando,
Thanks a lot for your feedback, I just did what you recommended and it works perfectly!
Cheers,
Julien
You’re welcome Julien! Glad that worked!