post_type incorrect for custom post type
I am trying to display a different template depending on the post type.
I have registered two custom post types called resource
and contact
. When I try to get the post type in search.php (using get_post_type()
), I always get back resource
post type, even when the post is definitely contact
.
Registering resource
function register_resource_post_type() {
$args = array(
'labels' = array('name' = __('Resources'), 'singular_name' = __('Resource'), 'add_new_item' = __('Add New Resource')),
'public' = true,
'supports' = array( 'title', 'custom-fields' ),
'show_in_rest' = true,
'rest_base' = 'resource-api'
);
register_post_type('resource', $args);
function custom_enter_resource_title( $input ) {
if ( 'resource' === get_post_type() ) {
return __( 'Enter resource title' );
}
return $input;
}
add_filter( 'enter_title_here', 'custom_enter_resource_title' );
}
add_action('init', 'register_resource_post_type');
Registering contact
function register_contact_post_type() {
$args = array(
'labels' = array('name' = __('Contacts'), 'singular_name' = __('Contact'), 'add_new_item' = __('Add New Contact')),
'public' = true,
'supports' = array( 'title', 'custom-fields' ),
'show_in_rest' = true,
'rest_base' = 'contact-api'
);
register_post_type('contact', $args);
function custom_enter_contact_title( $input ) {
if ( 'contact' === get_post_type() ) {
return __( 'Enter contact title' );
}
return $input;
}
add_filter( 'enter_title_here', 'custom_enter_contact_title' );
}
add_action('init', 'register_contact_post_type');
Search.php
while ( have_posts() ) :
the_post();
$post_type = get_post_type() ---- THIS IS ALWAYS resource
endwhile;