I am writing a plugin in which I am adding a custom post type(called ‘events’) using register_post_type. Additionally I want it to use single-event.php instead of the regular single.php.
The current structure of the plugin folder is :
- plugin-main-file.php
- single-event.php
I know its possible if I place it inside my theme directory, but I want it to be placed inside the plugin and utilize it.
How do I do it? Any custom function for that?
2 Answers
function get_custom_post_type_template($single_template) {
global $post;
if ($post->post_type == 'events') {
$single_template = dirname( __FILE__ ) . '/single-event.php';
}
return $single_template;
}
add_filter( 'single_template', 'get_custom_post_type_template' );
Source
Or you could use:
add_filter( 'template_include', 'single_event_template', 99 );
function single_event_template( $template ) {
if ( is_singular('event') ) {
$new_template = locate_template( array( 'single-event.php' ) );
if ( '' != $new_template ) {
return $new_template ;
}
}
return $template;
}
Source
Or you could use locate_template