in WordPress

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


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


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

Upgrade to access all content on Paulund

Members unlock all tutorials and snippets

Access to all downloadable content

Access to code examples before others

Sign Up Now

Already a member? Login here

Subscribe To The Weekly Newsletter

Get weekly updates to your email