How to Get Post Type within WordPress Loop

There are some times when you want to test for the post type of an item in your loop. You may use this in your functions.php file for taking dynamic actions for custom post types, or you may need to use it directly in your template.

Either way, here is how you would save the post type as a variable:

get_post_type( $post->ID );

You can also use the function conditionally like this:

if( get_post_type( $post->ID ) == 'custom_post_type_name'):
     // Do custom code here
endif;

This function can be particularly helpful if you’re needing to work a lot with custom post types.

3 thoughts on “How to Get Post Type within WordPress Loop

  1. jrobie23

    Thanks for this, Zac!! Stumbled across this and ’twas exactly what I was after. Also enjoy your courses on Team Treehouse! Keep up the great work!

    Like

    Reply

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s