Disable comments for images / media on WordPress.

Marc Wagner, July 22, 2022

WordPress automatically creates pages for images in your media library. On these pages, visitors can view and comment on the image. Not always this is desired, and often this is of course exploited by unwanted bots. In this tutorial, I show you how to disable the comments.

Disable WordPress comments with PHP. #

You should not always rely on a plugin, especially for minor problems. Plugins often open security gaps and have to be updated regularly, so they primarily cost resources and also affect the loading times of the website.

Using PHP, you can disable the comment function for any WordPress post type with just a few lines.

function disableCommentsForPostTypes( $open, $post_id ) {
	$listOfDisabledPostTypes = array(
		'attachment',
		//'post',
		//'page'
	);

	$post = get_post( $post_id );

	if(in_array($post->post_type, $listOfDisabledPostTypes)){
		return false;
	}
	return $open;
}
add_filter( 'comments_open', 'disableCommentsForPostTypes', 10 , 2 );

Note: This assumes that your theme uses the comments_open() function to check if comments are allowed.

The list of Post Types can be extended as you like. You can quickly and easily add more elements after “attachment” or remove the slashes “//” to include the posts and pages. The slashes serve as a one-line comment in PHP and are ignored when the page is loaded.

You just have to copy the above code into the “functions.php” of your child theme and save it. Now you are done, and unwanted comments are disabled.

Disable WordPress comments with the help of a plugin. #

If you want to use a plugin despite all the warnings, :) we recommend Disable Comments. You can install and activate the plugin as usual via “Plugins > Install” in your WordPress admin interface. The admin page of Disable Comments allows you to select the post types on which the comment function should be disabled.

image 2
Disable WordPress comments using Disable Comments plugin.

Clicking “Delete Comments” will additionally delete existing comments and disable commenting.

Note: Double is not better in this case. You should not use both variants. Disable Comments uses the same hooks and therefore the code would just be executed twice.

Did this little guide help you? Then leave us a short comment. We are happy about any feedback.

Avatar of Marc Wagner
Marc Wagner

Hi Marc here. I'm the founder of Forge12 Interactive and have been passionate about building websites, online stores, applications and SaaS solutions for businesses for over 20 years. Before founding the company, I already worked in publicly listed companies and acquired all kinds of knowledge. Now I want to pass this knowledge on to my customers.

Similar Topics

Comments

Leave A Comment