Controlling Comments on Image Pages in Twenty Eleven

I’ve been having problems with comment spam on the site. Strangely enough, they always seemed to come from one of the images on my very first gallery post, even though the post itself  doesn’t have a comment form (I have comments set to automatically close after three days).

Unwanted Comments on Image Attachment Pages

It turns out that image attachment pages don’t respect the site’s comment settings, at least not in the Twenty Eleven theme that I’m using as a parent. After another spam comment the other day, I found that Anthony Hortin, of Maddison Designs had solved the problem for the previous default WordPress theme, Twenty Ten. The solution involves adding a check to see if the attachment’s parent post still allows comments.

The Fix:

Change this:
<?php comments_template(); ?>
To this:
<?php if (comments_open($post->post_parent)) {
// Only show the Comments Form if the parent post has comments open
} ?>

The code is the same as Anthony’s; the only difference is that in Twenty Eleven, the file to modify is image.php, not attachment.php as it is in Twenty Ten. Since I’m already running a child theme, I made a copy of image.php and put it in my child theme folder, rather than modifying the parent theme file. This is the recommended way of making changes; but it does mean that if WordPress makes a change to the parent file, I won’t see the update. Hopefully, they’ll address the issue at some point.

Update, June 2012:

I’ve discovered there’s a significant drawback to this fix: Any comments posted during the open period are also hidden when comments closed. See this post for a further discussion and revised fix.