3

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?

1

2 Answers 2

1
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

6
  • Using locate_template the file will be searched in theme folder, where OP says it should be in plugin folder. My +1 is for first approach.
    – gmazzap
    Commented Aug 16, 2014 at 11:50
  • locate_template is used in many quality plugins to display templates. Commented Aug 16, 2014 at 12:10
  • It is used in many quality plugins to display templates from theme. See source: that function can't be used to load files from something external to theme, e.g. in plugin folder.
    – gmazzap
    Commented Aug 16, 2014 at 12:18
  • Can if the template is included in the plugin. Look at Genesis WooCommerce Connect. Commented Aug 16, 2014 at 12:28
  • That plugins support theming. It means that firts files are searched in theme (using locate_template) if the file is not found in theme, then the files are loaded from plugin folder using load_template
    – gmazzap
    Commented Aug 16, 2014 at 12:32
1

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');
0

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.