<?php
/**
* Removes comment spam anchors with empty nodeValues.
*
* @param $comment_content
*
* @return string
*/
function dmm_remove_empty_anchors_in_comments( $comment_content ) {
// Grab the comment content.
$dom_comment = new DOMDocument();
$dom_comment->loadHTML( $comment_content );
// Strip out the doctype and html wrapper.
$dom_comment->removeChild( $dom_comment->doctype );
$dom_comment->replaceChild($dom_comment->firstChild->firstChild->firstChild, $dom_comment->firstChild);
// Get a NodeList of the anchors in the comment.
$comment_anchors = $dom_comment->getElementsByTagName( 'a' );
// We have to go through the nodeList backward to delete items. Oherwise we will only get every other empty link.
for ( $i = $comment_anchors->length; --$i >=0; ) :
$comment_anchor = $comment_anchors->item( $i );
if ( trim ( $comment_anchor->nodeValue ) === '' ) :
$comment_anchor->parentNode->removeChild( $comment_anchor );
endif;
endfor;
// Save the comment without the spam links and send it back to be saved in the database.
$comment_content = $dom_comment->saveHTML();
return $comment_content;
}
// Grab the comment right before it is saved in the database.
add_filter( 'pre_comment_content', 'dmm_remove_empty_anchors_in_comments' );