Check For Custom Post Types Condiotionally In WordPress

WordPress provides you with the option of creating the CPT ( Custom Post Types ) for your project. So, what if you want to conditionally check for custom post types you have created for your project to display the content differently? Is it really possible at all? Yes, it is possible, and here we will describe about how to do it.

Check for Custom Post Types in WordPress inside the loop

WordPress has provided you with the function  get_post_type() for checking the custom post types or CPT within the loop. To get more information regarding this function, you can follow up this link.




For this function to work or function properly, you need to keep this function inside the WordPress loop, as shown in the example below:

Here, in the above example, we have added the  your-post-type as our custom CPT, which you might need to change it to your registered CPT. In this way, you can display your CPT content differently than the WordPress default post type.

Check for Custom Post Types in WordPress outside the loop

In order to check for custom post types outside the WordPress loop, the function to check it is same as above. The only difference on this is, you need to pass the post id inside the function  get_post_type(). For eg: if your post id is 5, then, the condition check for this would be as below:

Check for Custom Post Types in WordPress when viewing single page

While you are viewing the single page in WordPress, either be it post or page or your created CPT ( Custom Post Types ), you may also want to know about how to check for custom post types for these pages too, right? Well, for this too, WordPress has provided you with the function  is_singular() to check for it. For eg:

Here, in the above example, we have provided  your-post-type as our registered CPT to function as we require it to for our project. But, in your case, you might need to change it to your registered CPT and function that code accordingly as required. If you want to know more about this function then, you can follow this link.

Conclusion

If you have followed the above tutorial properly and is successful about how to check for custom post types in WordPress to function it accordingly to your site requirement, then, we can assume that you are more familiar with it than before. But, if you are still confused and want to know more about this, then please do drop the comment below and we will follow it up.

, , , , , , , , , , , , , , , , , ,

Post navigation

Bishal Napit

Bishal Napit is a WordPress theme developer from Tansen, Palpa, with a passion to learn more on WordPress.

Leave a Reply