Get The Current Post Type In WordPress

I recently had to make a theme that used similar code on different custom post types. For this I want to do something different depending on the post type.

To get the post type for the current post WordPress has a built in function that allows you to do this easily.

If you are inside the loop of a single post then you can just use the function get_post_type().

echo get_post_type( $post_id );

This function has 1 argument which is optional, this is the post ID. If you don't pass a argument into the function then it will use the global $post variable which is set inside the loop.

get_post_type returns a string of the post type of the post ID or the current post, from this value you can do a check on the post type to decide what you do with it, like the code below.

$post_type = get_post_type();

switch( $post_type )
{
    case 'task':
         // do code for task post type

    break;

    case 'todo':
         // do code for task post type

    break;
}

Now I can use this code in a common file used across multiple post types and do different things depending on the post type.

Advertise here 50% Off

Comment