get_post_type()WP 2.1.0

Gets the post type by the given ID (post, page, attachment).

The function can be used inside the WordPress Loop without passing the ID parameter, in which case the function will return the type of the current post that is in the global variable $post.

Article on the topic: about posts in WordPress

1 time — 0.000637 sec (slow) | 50000 times — 0.17 sec (very fast) | PHP 7.1.2, WP 4.7.5

No Hooks.

Returns

String|false. Post type or false.

Usage

get_post_type( $post );
$post_id(number/object)
Identifier of the post (ID) or Post object.
Default: null (current post)

Examples

0

#1 Get the post type whose ID is 121

$post_type = get_post_type( 121 );

echo $post_type; // post

/*
Displays: 
- 'attachment' if it is a media post.
- 'post' if it is a post
-  etc.
*/

Inside the WordPress Loop, the post type can be obtained without using this function:

echo $post->post_type;
0

#2 Default WordPress Post Type Names

Here are the default WP post type names.

post
page
attachment
revision
nav_menu_item

Full list with description see here.

0

#3 Conditional sentence to see if it is a post type.

if ( 'my_post_type' === get_post_type() ) {
	// it is my_post_type
}
0

#4 Get post_type outside The Loop

In some cases, such as when you’re outside The Loop, you may need to pass get_queried_object_id() as a parameter to get the post type of the current queried object:

$current_queried_post_type = get_post_type( get_queried_object_id() );

Changelog

Since 2.1.0 Introduced.

get_post_type() code WP 6.9

function get_post_type( $post = null ) {
	$post = get_post( $post );
	if ( $post ) {
		return $post->post_type;
	}

	return false;
}