Comments on attachments in WordPress

The way WordPress handles commenting on attachments (media) is a bit flaky. The comment status of attachment pages is set to the global default comment status when the media item is attached to a post. After that, there’s no way to change it! Surprising? Yes. There are a couple of truly ancient bug reports related to this, but they’ve received very little attention.

I ran into this issue when working on some of my comment-related plugins. So here’s how to fix it.

If you’re lazy

If you want to just disable comments on all media items, use the Disable Comments plugin.

If you want media items to inherit their comment status from their parent post, use the Comment Control plugin.

If you’re bored :)

To disable comments on all media items, put something like this in your theme’s functions.php file:

function filter_media_comment_status( $open, $post_id ) {
	$post = get_post( $post_id );
	if( $post->post_type == 'attachment' ) {
		return false;
	}
	return $open;
}

add_filter( 'comments_open', 'filter_media_comment_status', 10 , 2 );

If you want media items to inherit their comment status from their parent post:

function filter_media_comment_status( $open, $post_id ) {
	$post = get_post( $post_id );
	if( $post->post_type == 'attachment' && $post->post_parent ) {
		return comments_open( $post->post_parent );
	}
	return $open;
}

add_filter( 'comments_open', 'filter_media_comment_status', 10 , 2 );