Take the 2-minute tour ×
WordPress Development Stack Exchange is a question and answer site for WordPress developers and administrators. It's 100% free, no registration required.

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
add comment

2 Answers

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
add comment

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() )  {
        include($url);
        die();
    }   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! –  Ravi Kumar Sep 29 '13 at 10:55
add comment

Your Answer

 
discard

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.