Content & Posts PHP Beginner

Close Comments on Media Attachments

Stop comments on image and file attachment pages, a common target for spam bots.

Tested on WordPress 7.1 PHP 8.3 No plugin needed Updated
functions.php 7 lines
add_filter( 'comments_open', function ( bool $open, int $post_id ): bool {
	return 'attachment' === get_post_type( $post_id ) ? false : $open;
}, 10, 2 );

add_filter( 'pings_open', function ( bool $open, int $post_id ): bool {
	return 'attachment' === get_post_type( $post_id ) ? false : $open;
}, 10, 2 );

Where to add this

Recommended A code snippets plugin Survives theme changes and is easy to switch off.
Child theme At the end of your child theme's functions.php file.
Must-use plugin As a .php file in wp-content/mu-plugins, starting with <?php.

Always add PHP to a staging site first, or have FTP or file manager access ready, so you can undo it if something goes wrong.

Every uploaded file can have its own attachment page, and by default those pages accept comments. Real visitors rarely comment on them, but spam bots find them easily. This snippet closes comments and pingbacks on attachments only.

How it works

WordPress asks comments_open and pings_open whether a post accepts comments and pingbacks. The snippet answers no for attachments and leaves every other post type unchanged.

Things to watch

  • If attachment pages are turned off on your site (the default since WordPress 6.4), this is extra protection for direct comment submissions.
  • Existing attachment comments stay, but no new ones can be posted.

How to test it

Open an attachment page logged out. There should be no comment form.

This website uses cookies to enhance your browsing experience and ensure the site functions properly. By continuing to use this site, you acknowledge and accept our use of cookies.

Accept All Accept Required Only