How to Remove Hyperlinks from WordPress Comments
Here’s how to remove comment author’s hyperlink or a comment hyperlink or the comment author’s website field in WordPress. I’ve a snippet that can be added to the functions.php file which removes hyperlink from comment author, removes “Website Address” field in the comment form, and removes any HTML tags including hyperlinks from the comments themselves.
Here is the code you can add to your functions.php file:
// Remove hyperlink from comment author
add_filter('get_comment_author_link', 'remove_comment_author_link', 10, 3);
function remove_comment_author_link( $return, $author, $comment_ID ) {
return $author;
}
// Remove "Website" field from comment form
add_filter('comment_form_default_fields', 'unset_url_field');
function unset_url_field($fields){
if(isset($fields['url']))
unset($fields['url']);
return $fields;
}
// Remove hyperlinks from comments
add_filter( 'comment_text' , 'wp_strip_all_tags' );
Here’s what each part does:
The first section of the code removes the hyperlink from the comment author. It does this by filtering the get_comment_author_link hook to return just the author name without the link.
The second section removes the “Website” field from the comment form. It does this by filtering the comment_form_default_fields hook and unsetting the ‘url’ field.
The third section removes all HTML tags, including hyperlinks, from the comments. It does this by applying the wp_strip_all_tags function to the comment_text hook. Please note that this will remove all HTML tags, not just hyperlinks. If you need to keep some HTML tags and only remove hyperlinks, a different approach would be necessary, likely involving a regular expression to match and remove only “a” tags.
To remove only “a” tags from the comments (hyperlinks), you can replace the third section of the previous code with the following:
// Remove hyperlinks from comments
add_filter( 'comment_text' , 'remove_comment_links' );
function remove_comment_links($text){
$text = preg_replace('/(.*?)<\/a>/', "\\2", $text);
return $text;
}
This function uses preg_replace with a regular expression to match “a” tags and replace them with just the text between the tags (i.e., it removes the hyperlink but leaves the link text). The \\2 in the replacement string refers to the second captured group in the regular expression, which is the link text.
Remember to test this on a staging site or local development environment first, and not directly on a live site.