wordpress 评论图片 代码
时间 : 2024-01-06 08:53:02声明: : 文章内容来自网络,不保证准确性,请自行甄别信息有效性

最佳答案

要在WordPress评论中添加图片,你可以使用以下代码。

首先,在你的WordPress主题的`functions.php`文件中添加以下代码:

```php

function allow_comments_in_media_library( $allowed_types ) {

$allowed_types['attachment'] = 'attachment';

return $allowed_types;

}

add_filter( 'upload_mimes', 'allow_comments_in_media_library' );

接下来,打开`comments.php`文件,找到以下代码:

```php

<?php comment_text(); ?>

替换为以下代码:

```php

<?php

$comment_id = get_comment_ID();

$comment_text = apply_filters( 'comment_text', get_comment_text() );

$comment_text_with_images = preg_replace_callback(

'/<img [^>]*src=["\']?([^"\']*)[^>]*>/i',

function( $matches ) use ( $comment_id ) {

$image_url = $matches[1];

if ( ! current_user_can( 'edit_comment', $comment_id ) ) {

$image_url = wp_kses_post( $image_url );

}

return "<a href='$image_url' target='_blank'><img src='$image_url' /></a>";

},

$comment_text

);

echo $comment_text_with_images;

?>

这些代码将允许评论中的附件类型为`attachment`,并将评论中的图片转换为可点击的链接,点击链接会打开图片。

现在,当用户在评论框中插入图片时,图片将作为附件上传,并在评论中显示为可点击的链接。

请注意,这些代码只允许评论中的图片为附件,而不是从外部链接获取的图片。

其他答案

要在WordPress中实现评论中插入图片的功能,可以使用以下代码:

首先,在你主题中的`comments.php`文件中找到以下代码段:

```php

<?php comment_id(); ?>

在该代码段的下方,添加以下代码:

```php

<?php if ( $comment->comment_parent != 0 ) : ?>

<div class="comment-image">

<?php

$comment_parent = get_comment($comment->comment_parent);

if( !empty($comment_parent->comment_ID) ) {

$parent_avatar = get_avatar_url($comment_parent->comment_author_email);

echo '<img src="'. $parent_avatar .'" alt="'.$comment->comment_author.'" />';

}

?>

</div>

<?php endif; ?>

然后,在你的`style.css`文件中添加以下CSS样式:

.comment-image {
float: left;
margin-right: 10px;
width: 50px; /* 更改为你想要的图片宽度 */
}
.comment-image img {
max-width: 100%;
height: auto;
}

保存并上传你的主题文件和样式表文件。

这样,当有人在评论时,如果该评论是回复某个评论的,该回复评论的作者的头像将会显示在回复评论的左侧。