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.

Premium Service

If you seek a custom feature developed for your website or need 24/7 premium support to help you get started with your social network or Skadate dating website, save hours of searching online or wasting money on 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 in Touch

Leave a Reply