Page specific templates for Custom Post Types

By default WordPress allows us to use page specific templates by having files like

page-contact.php (page slug specific)

page-10.php (page ID specific)

but when it comes to custom post types, we’re left with no option but to use same template for all the custom posts of that custom post type.

In order to use post specific template for CPTs, we can have a single template file named

single-cpt.php (CPT is the name of your custom post type)

<?php
global $post;
if (file_exists(STYLESHEETPATH . '/single-' . $post->post_type . '-' . $post->post_name . '.php')) {
  include STYLESHEETPATH . '/single-' . $post->post_type . '-' . $post->post_name . '.php';
exit;
} else if (file_exists(STYLESHEETPATH . '/single-' . $post->post_type . '-' . $post->ID . '.php')) {
  include STYLESHEETPATH . '/single-' . $post->post_type . '-' . $post->ID . '.php';
exit;
}Code language: PHP (php)

Now the WordPress will check if there exists any post slug specific or ID specific template and use it.

Leave a comment

Your email address will not be published. Required fields are marked *