WordPress教程 · WPtech

WordPress评论内容实现插入图片

小编 · 9月16日 · 2019年 · ·

WordPress是不支持在评论中插入图片的,有时候留言评论时需要插入图片,或者我们自开发主题时,在评论时加入贴图功能,一起看下面的步骤来实现。

WordPress评论内容实现插入图片

1、在 functions.php 中加入以下代码

[erphpdown]
/*
*评论中插入图片
*/
add_action('comment_text', 'comments_embed_img', 2);
function comments_embed_img($comment) {
        $size = auto;
        $comment = preg_replace(array('#(http://([^\s]*)\.(jpg|gif|png|JPG|GIF|PNG))#','#(https://([^\s]*)\.(jpg|gif|png|JPG|GIF|PNG))#'),'<img src="$1" alt="" width="'.$size.'" height="" />', $comment);
        return $comment;
}
[/erphpdown]

这样的话,只要在评论中插入图片地址,就能显示图片了。

2、添加贴图按钮链接

在你的 comments.php 评论模板样式文件中,添加一个按钮或链接:

[erphpdown]
<a href="javascript:embedImage();" title="插入图片" alt="插入图片">插入图片</a>
[/erphpdown]

3、引入以下 js

在你主题的 Js 文件中引入以下代码:

[erphpdown]
// 评论贴图
function embedImage() {
	var URL = prompt('请输入图片 URL 地址:', 'http://');
	if (URL) {
		document.getElementById('comment').value = document.getElementById('comment').value + '' + URL + '';
	}
};
[/erphpdown]

这样就可以实现在评论中贴图了。

0 条回应

必须 注册 为本站用户, 登录 后才可以发表评论!