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

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

Last updated on May 5th, 2018 at 02:47 pm

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.

Did you get the answer you were searching for?

Save hours of searching online or wasting money testing unnecessary plugins, get in touch with me and let's discuss a suitable plan for your project. Best thing about this service is that you are never placed on hold and get to talk to an expereinced Oxwall/Skadate developer.

Get Answers for Free!

Ask a question related to this topic and get immediate answers from other community members in 48hrs or less. Contribute by answering members questions.

Ask Question
Premium Service

Whether it's a custom plugin, theme or dedicated support needed to get you started on your project, get professional 24/7 support tailored to your need.

Get in Touch

Or just leave a comment...

Leave a Reply