Comments on WordPress Image Pages, Revisited

Back in January, I posted a solution to a the problem of comment forms on image attachment pages remaining available even after comments on the parent post had closed, based on a solution by Anthony Hortin, of Maddison Designs. I was getting spam from the images on my first gallery page.

The solution I posted back then was to make the include of comments_template() conditional on the parent post’s comments being open. This worked, I stopped getting comments on old images. The code looked like this:

The original 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
} ?>

Unfortunately, the fix has a side effect: comments posted to an image during the “comments open” period also go away when the comments close. At the beginning of the month I posted a picture of some stuff I saw on the Charles that I couldn’t identify; a nice lady answered me, but her answer vanished when the comments closed.

It turns out the comments_template() function also outputs existing comments, so what you really want to do is still include comments_template(), but somehow, tell it comments are closed.

Fortunately, the function that returns the flag that indicates whether comments are open respects a filter, ‘comments_open’, so it became simply a matter of figuring out how to add that filter.

My first attempts to do so crashed. My function that tried to set the flag was trying to call comment_open() with the parent post, and crashed. Then I tried only applying the filter if the parent post’s comments were closed, using a function that simply returns false. It feels kludgy, but it does work.

The Revised Fix:

Change this:
<?php comments_template(); ?>
To this:
function close_image_post_comments() {return false;}

if (!comments_open($post->post_parent)) {
/* Only show the Comments Form if the parent post has comments open
by adding a filter to pass false to comments_open() */

add_filter( 'comments_open', 'close_image_post_comments', 10, 2 );
comments_template(); //bring in the comment output

This feels a little kludgy to me– I’d rather have the decision making in the function rather than the calling code, but it does work, and at this point, I’m not handy enough with PHP to figure out what I was doing wrong in the earlier version of my function.