admin管理员组

文章数量:1124383

Using 2016. For Search and Archive and Index, all attachment posts use content-attachment to display the excerpt... as expected.

But when I go to the actual attachment, it uses the image.php template. How can I get the post to use the same template as in archive or index or search? (content-attachment)?

Using 2016. For Search and Archive and Index, all attachment posts use content-attachment to display the excerpt... as expected.

But when I go to the actual attachment, it uses the image.php template. How can I get the post to use the same template as in archive or index or search? (content-attachment)?

Share Improve this question asked Mar 7, 2024 at 21:42 jchwebdevjchwebdev 7752 gold badges14 silver badges33 bronze badges 2
  • Assuming you're referring to the TwentySixteen theme, it doesn't have a content-attachment.php file. You could rename the image.php to something WordPress doesn't recognize and see what it falls back to. See the Template Hierarchy for more information. – Howdy_McGee Commented Mar 7, 2024 at 23:26
  • Right. I added a content-attachment.php and it works fine for archive, search, index. But for accessing the full post, it wants to use image.php. And if I remove that, it falls back to page.php. I was just curious how to get it to use my content-attachment.php to avoid having duplicate code. – jchwebdev Commented Mar 8, 2024 at 1:17
Add a comment  | 

1 Answer 1

Reset to default 1

There's a couple things you could do. If we follow the Template Hierarchy you could rename your content-attachment.php file to attachment.php and remove image.php. This will ensure that the image view will fallback to attachment.php.


If you want to use content-attachment.php then you could use the template_include hook to tell WordPress to load in which situation.

/**
 * Tell WordPress to load a specific template under specific circumstances.
 *
 * @param String $template_path
 *
 * @return String $template_path
 */
add_filter( 'template_include', function( $template_path ) {

    if( false !== strpos( $template_path, 'image.php' ) ) {

        // Path to your PHP file, relative to the twentysixteen theme (or child theme)
        // This would mean `content-attachmetn.php` is in the twentysixteen root, with page.php and singe.php
        $template_path = get_template_part( 'content-attachment' );
    }

    return $template_path;

} );

本文标签: