get_post_type()
Retrieves the post type of the current post or of a given post.
Uses: get_post()
1 time — 0.000637 sec (slow) | 50000 times — 0.17 sec (very fast) | PHP 7.1.2, WP 4.7.5
No Hooks.
Return
String|false
. Post type on success, false on failure.
Usage
get_post_type( $post );
- $post(int|WP_Post|null)
- Post ID or post object.
Default: global $post
Examples
#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;
#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.
#3 Conditional sentence to see if it is a post type.
if ( 'my_post_type' === get_post_type() ) { // it is my_post_type }
#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() get post type code WP 6.7.1
function get_post_type( $post = null ) { $post = get_post( $post ); if ( $post ) { return $post->post_type; } return false; }