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;

Topic loop wp-query custom-post-types Wordpress search

Category Web


Adding another possible solution for anyone else struggling with this. Removing the category of the post from the permalink - e.g. setting wordpress to use ONLY the post name - will cause this function to always return "post" for all custom post types.

You can avoid this by adding the category to the permalink in Settings->Permalink. If you still don't want the category to show, remove it with a plugin like redirection.


The comment

get_post_type() is not a complicated function

led me to disable the Relevanssi plugin that I was using for search and determined that "Create custom search result snippets" setting had been selected and was causing issues with the post type being returned. Once I unchecked this, everything worked.

About

Geeks Mental is a community that publishes articles and tutorials about Web, Android, Data Science, new techniques and Linux security.