How to Remove Automatic Linking of Comment URLs in WordPress

Home » Snippets » How to Remove Automatic Linking of Comment URLs in WordPress
0

Created with:

Visibility: 

public

Creator: WPTurbo Team

Customize with WPTurbo AI
X

Add Snippet To Project

New Project
Add To Existing Project

By default, WordPress automatically links any URLs entered in the comment section to a clickable link. While this may seem like a convenient feature, it can also lead to spam comments or unwanted links. In this article, we’ll show you how to remove the automatic linking of comment URLs on your WordPress site. This will not only help prevent spam, but also give you more control over the appearance of your comments section.

					function wpturbo_disable_comment_url_autolink( $text ) {
    $pattern = '/<as(?:.*?)href=['"](.*?)['"](.*?)(?:/)?>1</a>/si';
    $text = preg_replace( $pattern, '$1', $text );
    return $text;
}
add_filter( 'comment_text', 'wpturbo_disable_comment_url_autolink', 999 );
				

The code snippet above helps remove the automatic linking of URLs in comments on a WordPress site. This can be useful if you want to avoid users posting URLs that point to spammy or malicious websites.

The code uses the preg_replace() function to remove the HTML anchor tag (<a>) that automatically creates a hyperlink from a URL posted in the comment section. In other words, the function replaces the anchor tag with the original URL, which can be seen as plain text in the comment section.

function wpturbo_disable_comment_url_autolink( $text ) {
    $pattern = '/<as(?:.*?)href=['"](.*?)['"](.*?)(?:/)?>1</a>/si';
    $text = preg_replace( $pattern, '$1', $text );
    return $text;
}

First, we define a function called wpturbo_disable_comment_url_autolink() that accepts a variable $text, which corresponds to the content of the comment.

The $pattern variable contains a regular expression that captures the entire anchor tag for a URL. The pattern is designed to match both single-quoted and double-quoted URLs, and includes the optional trailing slash in the URL.

With preg_replace(), we replace the matched pattern with just the URL. The $1 reference in the replacement string refers to the URL that was matched by the first capture group in the pattern.

Finally, we return the modified $text value, which no longer contains any HTML anchor tags for URLs.

add_filter( 'comment_text', 'wpturbo_disable_comment_url_autolink', 999 );

Lastly, we add this function to a WordPress filter hook using add_filter(). This ensures that the function is executed whenever a comment is displayed on the site. The priority of this filter is 999, which ensures it runs after other filters that might modify the comment text.

Register an account to save your snippets or go Pro to get more features.