WordPress 评论禁用 HTML 标签

禁用评论 HTML 标签
禁用评论 HTML 标签

在默认情况下,WordPress 评论中允许使用部分 HTML 标签,比如<a><em><strong> 等。如果你留意过垃圾评论,他们大部分都包含这些标签。这是因为大多数的垃圾评论都是由机器人和脚本使用 HTML 标签制作的。我们仅仅简单的在 WordPress 评论中禁用 HTML 标签,就可阻止大部分的垃圾评论,在本文中我们将向您展示如何在 WordPress 评论中禁用 HTML 标签。

请注意,本文所写的代码仅仅是禁用了有效的 HTML 标签,有些人还可以通过

&lt;a&gt;&lt;em&gt;&lt;strong&gt;

尽管以上代码会展示为正常的 HTML 标签,但是它们并不能正常工作,假如有人使用了strong 标签,并不会加粗文字,另外并不是所有的垃圾机器人都会去做这些事,因为这对他们来说浪费时间而且没有任何益处。

我们只需一行代码即可禁用 WordPress 评论中的 HTML 标签,即将如下代码添加到 functions.php 文件中即可。

<?php
/**
 *  Remove the ability for users to post HTML.
 *
 *  @author 智慧宫
 *  @link   https://lerm.net
 */
add_filter( 'pre_comment_content', 'wp_specialchars' );

这一行代码即可禁止用户在 WordPress 评论中使用 HTML 标签。

网上还有一种方法同样可以禁用 WordPress 评论中 HTML 标签。您只需将下面的代码添加到 functions.php 文件中:

<?php
 // This will occur when the comment is posted
function plc_comment_post( $incoming_comment ) {
	// convert everything in a comment to display literally
	$incoming_comment['comment_content'] = htmlspecialchars( $incoming_comment['comment_content'] );

	// the one exception is single quotes, which cannot be #039; because WordPress marks it as spam
	$incoming_comment['comment_content'] = str_replace( "'", '&apos;', $incoming_comment['comment_content'] );

	return( $incoming_comment );
}

	// This will occur before a comment is displayed
function plc_comment_display( $comment_to_display ) {

	// Put the single quotes back in
	$comment_to_display = str_replace( '&apos;', "'", $comment_to_display );

	return $comment_to_display;
}
add_filter( 'preprocess_comment', 'plc_comment_post', '', 1);
add_filter( 'comment_text', 'plc_comment_display', '', 1);
add_filter( 'comment_text_rss', 'plc_comment_display', '', 1);
add_filter( 'comment_excerpt', 'plc_comment_display', '', 1);

以上这两段代码测试都有效果,选择其中一个使用就可以了。

发表评论

游客欢迎您123