How do I Make a custom post type get a custom post template in a plugin

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?

Solutions Collecting From Web of "How do I Make a custom post type get a custom post template in a plugin"

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

This is what I’ve always done. Not sure if you need both $wp_query and $post but it’s always worked for me.

Just put this in plugin-main-file.php

/**
 * Add single template for events post type plugin
 */
function custom_template_events_post_type_plugin($single) {
      global $wp_query, $post;
      if ($post->post_type == "events"){
        $template = dirname( __FILE__ ) . '/single-event.php';
        if(file_exists( $template ))
            return $template;
      }
        return $single;
    }
    add_filter('single_template', 'custom_template_events_post_type_plugin');