[wp-hackers] Template Hierarchy In A Plugin

Mike Little wordpress at zed1.com
Sun Aug 7 15:40:09 UTC 2011


On Fri, Aug 5, 2011 at 23:25, Alex Andrews <awgandrews at gmail.com> wrote:

>  Dear all,
>
> What is the best way to take advantage of the way in which WordPress
> automatically guesses, and correctly loads the right template for a custom
> post type, but within a plugin rather than a theme?
>
> So in a plugin I load a series of custom post types, and tell WordPress
> where the template files for them are, which it then loads in an automated
> manner. So album-single.php loads as we would expect if it were under the
> template directory and so on?
>
> I attempted to Google this, but obviously quite difficult to get through
> the thickets of results to it out!
>
> Thanks for the help,
>
> Alex
>
>
If I understand you correctly, you want to load a template file to display a
custom post type from your plugin directory, whereas WordPress would
normally look for the appropriate template file in a theme.

You should look at the 'template_include' filter. Something like this code
(not tested) might work.

add_filter( 'template_include', 'template_include' );
function my_template_include( $template ) {
if ( 'album' === get_query_var( 'post_type' ) ) {
if ( is_single() ) {
 return dirname( __FILE__ ) . '/single-album.php';
} else { // loop
 return dirname( __FILE__ ) . '/archive-album.php';
}
}
 return $template;
} // end my_template_include


Mike
-- 
Mike Little
http://zed1.com/


More information about the wp-hackers mailing list