WordPress Function to Check if Current Post is a Specific Post Type

WordPress Function to Check if Current Post is a Specific Post Type

I’m not very sure how to phrase the title of this post but this a function that basically checks if the post type of the current post or of a given post matches the post type you have specified.

I created this function to check post-type in my single.php. I had a custom post type called devbio_projects and I needed a different template file to display single projets in my theme. Something like the snippet below:

if( post_is_custom_post_type( 'devbio_projects') )
{
	get_template_part( 'template-parts/content', 'project' );
}
else
{
	get_template_part( 'template-parts/content', 'single' );
}

However, it’s not limited to this purpose. If you are looking to achieve something similar to is_home() wp function for a custom post-type, here is your code:

/**
 * Checks if post is wp custom post type
 *
 * @param string $type
 * @param int $post = null
 */
function post_is_custom_post_type( $postType, $post = null )
{
	$current_post_type = !empty( $post ) ? get_post_type( $post ) : get_post_type();
	
	if( $current_post_type == $postType )
	{
		return true;
	}
	
	return false;
}

Parameters

  • $postType
    • (string) (required) The post type
    • Default: None
  •  $post
    • (int|WP_Post|null) (Optional) Post ID or post object. Default is global $post.
    • Default value: null

Return

  • (string|false) Post type on success, false on failure.

See get_post_type() function on wp repository on how to retrieve current or given post type.

Leave a Reply