0

I am creating a Custom Post Type using a custom plugin. One of the requirement of the custom post type is to be presented in a table layout for print / email purpose.

It seems that the logical solution for this situation is to include a specific template file in the plugin which will be used on single Custom Post Type query instead of the single.php / index.php provided in the theme.

How can I use a file in my plugin as a replacement for single.php / index.php on single custom-post-type query?

Thank you in advance.

3

The way I handle these is to store to use template_include to conditionally pass my plug-in template. One of these conditions is that the corresponding file hasn't already been found by WordPress (i.e. isn't present in the theme folder).

This means that users can over-ride the plug-in template with a theme-specific one by simply creating the appropriate template in their theme. As such they can make alterations and not worry about plug-in updates:

The following uses single-event.php instead of single.php when viewing a single post of 'event' post type.

/**
 * Checks to see if appropriate templates are present in active template directory.
 * Otherwises uses templates present in plugin's template directory.
 */
add_filter('template_include', 'wpse72544_set_template');
function wpse72544_set_template( $template ){

    /* 
     * Optional: Have a plug-in option to disable template handling
     * if( get_option('wpse72544_disable_template_handling') )
     *     return $template;
     */

    if(is_singular('event') && 'single-event.php' != $template ){
        //WordPress couldn't find an 'event' template. Use plug-in instead:
        $template = 'absolute/path/to/plugin/template/single-event.php';
    }

    return $template;
}

Note that all the main query conditionals (is_* functions) are available to you at this point.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

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