The post_type_exists() WordPress PHP function determines whether a post type is registered.
Usage
post_type_exists('custom_post_type');
Example:
$exists = post_type_exists('book');
// returns true if 'book' is a registered post type
Parameters
$post_type (string)– Required. The post type name you want to check if it exists.
More information
See WordPress Developer Resources: post_type_exists()
Examples
Check if a custom post type ‘product’ exists
if (post_type_exists('product')) {
echo 'The "product" post type exists.';
} else {
echo 'The "product" post type does not exist.';
}
Conditional display of a post type archive link
if (post_type_exists('event')) {
echo '<a href="' . get_post_type_archive_link('event') . '">View all events</a>';
}
Create a custom post type only if it doesn’t exist
if (!post_type_exists('portfolio')) {
register_post_type('portfolio', $args);
}
Check multiple post types for existence
$post_types = array('product', 'event', 'book');
foreach ($post_types as $post_type) {
if (post_type_exists($post_type)) {
echo "The post type '{$post_type}' exists.<br>";
} else {
echo "The post type '{$post_type}' does not exist.<br>";
}
}
Use post type existence check in a plugin activation hook
function my_plugin_activation() {
if (!post_type_exists('custom_post')) {
// Register the custom post type or handle other setup tasks
}
}
register_activation_hook(__FILE__, 'my_plugin_activation');