Correcting Hyperlink Problems

Most Web sites use underline to style hyperlinks. When producing content in WordPress, highlighting words and phrases quickly to add hyperlinks can lead to hyperlinking (and underlining) the spaces before and after your anchor text.

For some, this is enough to convince them to hide underlines for hyperlinks, even though that may not be desired.

Here's a quick snippet that filters through blog post content and ensures that you don't have any spaces on the wrong side of the tag or between a closing tag and punctuation. Add this in your Theme Functions (functions.php) file:

/**
 * Prevents underlined spaces to the left and right of links.
 *
 * @param string $content Content
 * @return string Content
 */

function my_anchor_text_trim_spaces( $content ) {
// Remove spaces immediately after an <a> tag.
$content = preg_replace( '#<a([^>]+)>\s+#', ' <a$1>', $content );
// Remove spaces immediately before an </a> tag.
$content = preg_replace( '#\s+</a>#', '</a>', $content );
// Remove single spaces between an </a> tag and punctuation.
$content = preg_replace( '#</a>\s([.,!?;])#', '</a>$1', $content );
return $content;
}
add_filter( 'the_content', 'my_anchor_text_trim_spaces' );

image HTML ignores more than one space in a row (also more than one tab character and line break), unless you're using the ‘pre’ element or nonbreaking space entities (‘&nbsp;’). Therefore, even ...

Get WordPress® All-in-One For Dummies® now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.