WordPress编辑评论时修改评论者的IP地址

知更鸟
知更鸟
知更鸟
站长
2558
文章
0
粉丝
WordPress评论108阅读模式

默认WordPress后台编辑评论时,不能修改评论者的IP,只能进入数据库wp_comments表中修改。可以通过下面的代码在编辑评论页面添加IP修改表单。

WordPress编辑评论时修改评论者的IP地址

将代码添加到当前主题functions.php函数模板中即可。

// 后台评论编辑页添加IP输入框
add_action( 'add_meta_boxes_comment', 'custom_comment_ip_meta_box' );
function custom_comment_ip_meta_box() {
	// 仅管理员可见
	if ( ! current_user_can( 'moderate_comments' ) ) {
		return;
	}

	add_meta_box(
		'comment-ip-address',
		'评论 IP 地址',
		'custom_render_comment_ip_meta_box',
		'comment',
		'normal',
		'high'
	);
}

// 渲染IP输入框
function custom_render_comment_ip_meta_box( $comment ) {
	// CSRF 安全验证
	wp_nonce_field( 'save_comment_ip_action', 'comment_ip_nonce' );

	// 获取当前评论IP
	$ip = $comment->comment_author_IP;
	?>
	<div class="comment-ip-field">
		<p>
			<label for="comment_author_ip" class="strong">IP 地址:</label>
			<input 
				type="text" 
				name="comment_author_ip" 
				id="comment_author_ip" 
				value="<?php echo esc_attr( trim( $ip ) ); ?>" 
				class="regular-text"
				placeholder="例如:192.168.1.1"
			/>
		</p>
	</div>
	<?php
}

// 保存IP地址
add_action( 'edit_comment', 'custom_save_comment_ip' );
function custom_save_comment_ip( $comment_id ) {
	if ( ! current_user_can( 'moderate_comments' ) ) {
		wp_die( '您没有权限修改评论IP' );
	}

	if ( ! isset( $_POST['comment_ip_nonce'] ) || ! wp_verify_nonce( $_POST['comment_ip_nonce'], 'save_comment_ip_action' ) ) {
		wp_die( '安全校验失败,请刷新页面重试' );
	}

	if ( ! isset( $_POST['comment_author_ip'] ) ) {
		return;
	}

	// 获取并清理IP
	$raw_ip = trim( $_POST['comment_author_ip'] );
	// 验证是否为合法IP地址
	if ( ! empty( $raw_ip ) && ! WP_Http::is_ip_address( $raw_ip ) ) {
		wp_die( '请输入合法的 IP 地址' );
	}

	// 更新IP字段
	global $wpdb;
	$wpdb->update(
		$wpdb->comments,
		array( 'comment_author_IP' => $raw_ip ),
		array( 'comment_ID' => $comment_id )
	);
}

适用场景

当主题有评论IP归属地显示功能,管理员可以自己加评论,通过修改IP冒充评论者来自五湖四海....

 

本站文章大部分为原创,用于个人学习记录,可能对您有所帮助,仅供参考!

weinxin
我的微信
微信号已复制
版权声明
本站原创文章转载请注明文章出处及链接,谢谢合作!
 
知更鸟
匿名

发表评论

匿名网友

拖动滑块以完成验证