Skip to content

Instantly share code, notes, and snippets.

@joshuadavidnelson
Last active February 4, 2026 17:47
Show Gist options
  • Select an option

  • Save joshuadavidnelson/8291503 to your computer and use it in GitHub Desktop.

Select an option

Save joshuadavidnelson/8291503 to your computer and use it in GitHub Desktop.
Checks if the current post is a custom post type, returns boolean
<?php
/**
* Checks if a post is a custom post type, returns boolean.
*
* @author Joshua David Nelson
* @link http://joshuadnelson.com/code/is_custom_post_type/
*
* @param int $post_id The post id, defaults to the current post.
* @return bool
*/
if ( !function_exists( 'is_custom_post_type' ) ) {
function is_custom_post_type( $post_id = 0 ) {
// find custom post types
$args = array(
//'public' => true, // -- uncomment if you only want "public" cpts
'_builtin' => false,
);
$public_custom_post_types = get_post_types( $args, 'names' );
// if there are no custom post types, then the current post can't be one
if( empty( $public_custom_post_types ) )
return false;
// access global variable if the passed post id invalid or not provided.
$post_id = absint( $post_id ) ?: get_the_ID();
// if we don't have a valid id, we're in a context that this function works.
if ( ! $post_id ) {
return false;
}
// get the current post type, returns a string or false on failure
$post_type = get_post_type( $post_id );
// check if current post type is a custom post type
if ( $post_type && in_array( $post_type, $public_custom_post_types ) ) {
return true;
}
// if all else fails, return false
return false;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment