WordPress Development Stack Exchange is a question and answer site for WordPress developers and administrators. Join them; it only takes a minute:

Sign up
Here's how it works:
  1. Anybody can ask a question
  2. Anybody can answer
  3. The best answers are voted up and rise to the top

I have made a custom image.php for a gallery plugin I'm creating. My dilemma is that I currently have to have my customized image.php in the theme folder for it to work. Is there a way to tell Wordpress to utilize a template file outside of the theme folder to process attachments?

share|improve this question

Filter attachment_template and return your custom path. For details, see wp-includes/template.php, function get_query_template().

Sample code:

add_filter( 'attachment_template', function( $template )
    global $post;

    // inspect $post object to determine the correct template
    // and change the file path, then:
    return $template;
share|improve this answer

You can use this code, it first looks in theme folder if not found then in plugins folder.

Sample code:

add_action( 'template_redirect', 'weinvent_template_redirect' );

/*Template fallback*/
function weinvent_template_redirect() {

    global $wp, $wp_query;
    $plugindir  =   dirname( __FILE__ );

    if( is_attachment() ) {
        $templatefilename   =   'image.php';
        if( file_exists( TEMPLATEPATH . '/' . $templatefilename ) )  {
            $return_template    =   TEMPLATEPATH . '/' . $templatefilename;    
        }   else    {
            $return_template    =   $plugindir . '/templates/' . $templatefilename;

        do_theme_redirect( $return_template );


function do_theme_redirect( $url ) {

    global $post, $wp_query;
    if( have_posts() )  {
    }   else    {
        $wp_query->is_404   =   true;
share|improve this answer
This is not good: 1. template_redirect runs on every template, so the callback is called too often. 2. your die() prevents the important action shutdown, so this will break many plugins. – toscho Sep 29 '13 at 10:45
Thank you toscho! – Webloper Sep 29 '13 at 10:55

Your Answer


By posting your answer, you agree to the privacy policy and terms of service.

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