If you want to use a particular template for your custom post type (CPT) then the best choice is usually to create a new template such as single-{post-type}.php
. (Check out the WordPress handbook for more details about custom post type template files). But in some cases you may want to programmatically determine which template to load for your CPTs. One situation where this is a good idea is when you want to use the same template for several CPTs. In this case you can use the following code instead of creating multiple template files and renaming them all.
<?php | |
add_filter( 'template_include', 'your_custom_cpt_template', 99 ); | |
/** | |
* Load an alternative template file for a given post type | |
* | |
* @param string $template path to the default template | |
* @return string $template path to the default template | |
* @return string $custom_template path to the custom template | |
*/ | |
function your_custom_cpt_template( $template ) { | |
if ( ! is_singular( array( 'your_cpt_1', 'your_cpt_2' ) ) ) { // Change 'your_cpt_x' to the slug of your custom post type(s) | |
return $template; | |
} | |
$custom_template = locate_template( array( 'your_cpt_template.php') ); // Change 'your_cpt_template.php' to the file name of your template (e.g., 'page_landing.php') | |
if ( ! $custom_template ) { | |
return $template; | |
} | |
return $custom_template; | |
} |
First we are checking if a singular post of our selected CPTs is being displayed. If not, then we revert to the default template. Next we look up the path to the template that we want to use, and use that template if the path exists. If the path does not exist, then again we revert to the default template.
Leave a Reply