Conditional checks for custom post types
I came across a tutorial the other day on a popular WordPress blog about checking the post type of a post in WordPress. The tutorial used a [broken] custom function for something that already exists in WordPress. Unfortunately, the correction I left in the comments was not used to amend to the tutorial, so I figured I’d share the correct way of doing this with others.
This tutorial will walk you through the steps of properly checking the post type of a post and in what situations to use the functions presented.
Checking the post type within The Loop
Sometimes, you may need to check a post type of a given post within the posts loop. This would most commonly be used within a theme’s templates, but there are other applications for it.
For this, you need the get_post_type() function, which returns the name of the post type.
The following code checks the post type of the current post in the loop and runs some code if the post type is either movie
or book
.
<?php
if ( 'movie' == get_post_type() ) {
/* Custom code for 'movie' post type. */
} elseif ( 'book' == get_post_type() ) {
/* Custom code for the 'book' post type. */
}
?>
Yes, it’s really that simple. If you know how to use if/else statements in PHP, you’re good to go.
Checking a post type outside of The Loop
Checking a post type either inside or outside of The Loop is nearly the same. You’d use the same function in this case: get_post_type()
. However, this time, you’d need to either put in the post object or the post ID of the specific post you want to check the post type for.
Suppose you wanted to check if the post with the ID of 100
has the product
post type. You’d use the following code to do so.
<?php
if ( 'product' == get_post_type( 100 ) ) {
/* Run some code if this post has a post type of 'product'. */
}
?>
Checking a singular post’s post type
If viewing a single/singular view of a post, WordPress has a nifty function that handles this check for you: is_singular(). This function’s main purpose is to check if viewing a singular post. However, it can also be used to check if viewing a singular post of a given post type by entering the $post_type
parameter as shown in the following code snippet.
is_singular( 'post' )
You can also check for multiple post types by entering an array of post types as the $post_type
parameter as shown in the following code.
is_singular( array( 'post', 'page', 'attachment' ) )
Suppose you wanted to check if a user was viewing a singular post with the post type of testimonial
. You can use the next code sample to perform this check.
<?php
if ( is_singular( 'testimonial' ) ) {
/* Run some code if viewing a singular testimonial. */
}
?>
There you have it. It’s fairly easy to run these types of checks, and the required functions are already built into WordPress for you.