Support » Themes and Templates » One template for post attachments and a different one for page attachments?

Viewing 3 replies - 1 through 3 (of 3 total)
  • Moderator keesiemeijer

    (@keesiemeijer)

    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.

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

    Moderator keesiemeijer

    (@keesiemeijer)

    You’re welcome 🙂

Viewing 3 replies - 1 through 3 (of 3 total)
  • The topic ‘One template for post attachments and a different one for page attachments?’ is closed to new replies.