2

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;
?>
3

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.

  • Great clarification. It seems odd to have something in the template hierarchy that behaves differently. YOu can probably guess what I did: copy the single.php to attachment.php and then discovered the behavior. As a follow up: I'm trying to find a good filter to update the <img> tags in all posts. Is there a filter you'd recommend? – funwhilelost Oct 10 '14 at 16:20
  • Not sure what you mean about filter, please ask new question if that makes sense for it. :) – Rarst Oct 10 '14 at 16:34
  • Yeah, I might open a larger topic in general: "what's the best way to alter page content after it's left the editor?" I've seen filters, capturing a buffer and altering, JavaScript, etc. – funwhilelost Oct 10 '14 at 17:00

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.