WordPress.org

Ready to get started?Download WordPress

Forums

[resolved] One template for post attachments and a different one for page attachments? (4 posts)

  1. Cathedral City Guide
    Member
    Posted 1 year ago #

    I have recently created an attachment.php template for my site which is working fine.

    However I would like to use one template for images attached to a page, and a different template for images attached to a post.

    For example here is an image attached to a page: http://www.cathedralcityguide.co.uk/the-cities/bristol/bristol-harbour/
    and here is an image attached to a post: http://www.cathedralcityguide.co.uk/2013/01/happy-new-year-from-cathedral-city-guide/fireworks-small/

    Looking at the template hierarchy I can't work out to do this. Is it possible? Any help much appreciated!

  2. keesiemeijer
    moderator
    Posted 1 year ago #

    Create a page_attachment.php and a post_attachment.php file and use this in your theme's functions.php:

    add_filter( 'template_include', 'attachment_template', 99 );
    function attachment_template( $template ) {
    	if ( is_attachment() ) {
    		global $post;
    		if ( isset( $post->post_parent ) && $post->post_parent ) {
    			$parent = get_post( $id = $post->post_parent );
    			if ( $parent->post_type == 'page' ) {
    				$template = locate_template( array( 'page_attachment.php' ) );
    			} elseif ( $parent->post_type == 'post' ) {
    				$template = locate_template( array( 'post_attachment.php' ) );
    			}
    		}
    
    	}
    	return $template;
    }

    This will make WordPress use the separate files for page and post attachments.

    btw:
    consider creating a child theme instead of editing your theme directly - if you upgrade the theme all your modifications will be lost.

  3. Cathedral City Guide
    Member
    Posted 1 year ago #

    Thanks keesiemeijer, that's brilliant and works perfectly! I really appreciate your help.

  4. keesiemeijer
    moderator
    Posted 1 year ago #

    You're welcome :-)

Topic Closed

This topic has been closed to new replies.

About this Topic