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

    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.

Back to top ^

Join Paulund

  • Get access to 100s of premium tutorials and downloadable content
  • Members content consists of Premium WordPress plugins, CSS packages, jQuery packages, tutorial demo files and templates for 100s of web development tutorials
  • In-depth development tutorials
  • Priority tutorial requests
  • Priority email development support
  • No ads

Here at Paulund you'll find Web Development tutorials and snippets focusing mainly on PHP, WordPress and CSS. Members will get access to premium tutorials that go into more detail about development with these languages. You will also get access to downloadable premium content based on the tutorial.

Join Paulund

Leave a Reply

Your email address will not be published. Required fields are marked *