I am looking for a way to test if a post is a custom post type. For example, in, say, the sidebar I can put in code like this:
if ( is_single() ) {
// Code here
}
I want code testing for only a custom post type.
I am looking for a way to test if a post is a custom post type. For example, in, say, the sidebar I can put in code like this:
if ( is_single() ) {
// Code here
}
I want code testing for only a custom post type.
You must be logged in to post a comment.
Here you are:
get_post_type()
and thenif ( 'book' == get_post_type() ) ...
as per Conditional Tags > A Post Type in Codex.The above is
true
when viewing a post of the custom post type:book
.The above is
true
when viewing a post of the custom post types:newspaper
orbook
.These and more conditional tags can be viewed here.
To test if a post is any custom post type, fetch the list of all not built-in post types and test if the postâs type is in that list.
As a function:
Usage:
Add this to your
functions.php
, and you can have the functionality, inside or outside of the loop:So you can now use the following:
If for any reason you already have access to the global variable $post, you can simply use
If you want a wild card check for all your custom post types:
This way you don’t need to know the name of your custom post. Also the code still work even if you change the name of your custom post later.
To determine the $post_type easily inside a function, you need to call the global post var first, here is an example:
I have been reading all the answers, they are usable, but the most simple that you can use to check if the post is standard or custom, you can just go with:
The first expression is for standard post, and the second one is for any custom post.
I hope it can help someone.