Stuff & Things

How To: Test for a WordPress Custom Post Type

There instances where a WordPress developer may need to test whether a specific post is a Custom Post Type.  You can test whether a post is a specific Custom Post Type from within the loop, outside of the loop, or from within the Single Post view (single.phpsingle-*.php, and more).

Testing for a Custom Post Type from within The Loop

In this example, we will be using the get_post_type() function to determine whether a post is a ‘photo’ or ‘illustration’ Custom Post Type.

if ( get_post_type() == 'photo' ) { echo 'Post is type: photo'; }
elseif ( get_post_type() == 'illustration' ) { echo 'Post is type: illustration'; }

Testing for a Custom Post Type outside of The Loop

To test for a Custom Post Type from outside of the loop, we need to know the post_id.  In this example, the post_id we are testing is “1”.

if ( get_post_type(1) == 'photo' ) { echo 'Post is type: photo'; }
elseif ( get_post_type(1) == 'illustration' ) { echo 'Post is type: illustration'; }

Testing for a Custom Post Type within single.php

The built-in WordPress function is_singular() will test whether any of the following is true for a page: is_single()is_page() or is_attachment().  The is_singular() function also has the ability to test whether a page is a specific type.  You can test whether a page is a blog post or a ‘photo’ type in the following example:

if ( is_singular('post') ) { echo 'Post is type: post'; }
elseif ( is_singular('photo') ) { echo 'Post is type: photo'; }
elseif ( is_singular('illustration') ) { echo 'Post is type: illustration'; }

You can also test a page against any number of Custom Post types by using arrays:

if ( is_singular(array( 'post', 'photo', 'illustration' )) ) { echo 'Post is type is either: post, photo, or illustration'; }

You can learn more about the WordPress functions used in this post (get_post_type() and is_singular()) at the WordPress.org Codex.