Archived topic
Custom no-results.php for post type using hook.
3 replies · Started by Mike on April 26, 2022
Hi,
I have a custom post type "Events" and when we don't have any posts I want it to display a nice error saying "No Upcoming Events"
So far I have this which I know with some inline styling could work:
add_action( 'generate_before_content','events_no_posts_found' );
function events_no_posts_found(){
if(is_post_type_archive('events') && empty(get_posts('post_type=events'))){
echo '
<style>
/* I will put styling here to display:none the old stuff and show this stuff below */
</style>
<header class="entry-header" aria-label="Content">
<h1 class="entry-title">No Upcoming Events</h1>
</header>
<div class="entry-content">
<p>Sorry, we don't have any upcoming events. Check back again soon!</p>
</div>
';
}
}
This works great, but, I am wondering if there is a more elegant way of doing it?
I was hoping for a way to not render the default .entry-header and .entry-content in the snippets PHP rather than using CSS display:none; to hide it.
One thing I did try was using add_filter instead of add_action, then adding exit; to the bottom of my function. This worked but also stopped my footer and everything else afterward from processing!
Any ideas of the best way to go about this?
I did try looking for functions to change the title on a specific page etc but couldn't find anything...
Hi there.
how was the CPT Template created ?
Like this:
function events_custom_post_type() {
register_post_type('events',
array(
'labels' => array(
'name' => __('Events', 'textdomain'),
'singular_name' => __('Event', 'textdomain'),
),
'public' => true,
'has_archive' => true,
'rewrite' => array( 'slug' => 'events' ),
'menu_icon' => 'dashicons-calendar',
)
);
}
add_action('init', 'events_custom_post_type');
Could i see the page with no results ?