Last active
January 7, 2018 07:19
-
-
Save danemorgan/78a2badf7cad2566c6a5c0d9458f3166 to your computer and use it in GitHub Desktop.
Remove empty anchor #spam from #comments. #WordPress
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?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' ); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment