the_content() behavior on attachment.php versus single.php

I’m having some trouble getting the_content() to work on attachment.php. I have a template page that has the basic loop and simple calls the_content() in the loop to display the post.

Scenario 1

Load an attachment page with the template file single.php and it will output the image tag and run it through prepend_attachment.

Scenario 2

Load an attachment page with the template file attachment.php and it will output nothing from the_content(). I’ve also verified that it doesn’t called the prepend_attachment or the_content filters.

Can someone explain what is going on here?

<?php
if (have_posts()) : while (have_posts()) : the_post();
  the_content();
endwhile; endif;
?>

1 Answer
1

This is correct behavior, if your attachment doesn’t actually have anything in post_content field (which is quite common).

When post–centric templates run, prepend_attachment() is used as filter to “emulate” post content. This is not the case with template “intended” for attachments.

If you look at template-loader.php:

elseif ( is_attachment()     && $template = get_attachment_template()     ) :
    remove_filter('the_content', 'prepend_attachment');

the filter is explicitly removed.

So there is no “fake” content generated for you. You will have to decide and express in code what do you actually want shown for attachments, or simply add back the filter if that is what you want.

Leave a Comment