WordPress 技巧:设置好评并输出

2023-04-14 16:25:04 浏览数 (1)

一些评论比较多的媒体站,管理员会把一些用户写的好评单独输出在侧边栏,但是怎么设置好评和输出呢?我们可以在 WordPress 后台评论管理界面评论管理区添加一个新的好评动作,并且通过 WP_Comment_Query 这个 Class 输出所有好评。

详细代码如下:

代码语言:javascript复制
<?php
/*
Plugin Name: WPJAM 好评
Plugin URI: http://blog.wpjam.com/m/wpjam-good-comments/
Description: 管理员可以在后台留言列表设置某条评论为好评,在前台通过<code>wpjam_get_good_comments</code>调用所有好评的评论。
Version: 0.1
Author: Denis
Author URI: http://blog.wpjam.com/
*/

add_filter('comment_row_actions','wpjam_good_comments_comment_row_actions',10,2);
function wpjam_good_comments_comment_row_actions($actions, $comment ){
    if(get_comment_meta( $comment->comment_ID, 'good_comment',true) == '1'){
        $actions['good_comment'] = '<a href="'.home_url('/wp-admin/edit-comments.php?good_comment=0&comment_id='.$comment->comment_ID).'">取消好评</a>';
    }else{
        $actions['good_comment'] = '<a href="'.home_url('/wp-admin/edit-comments.php?good_comment=1&comment_id='.$comment->comment_ID).'">好评</a>';
    }
    return $actions;
}

add_action('admin_head','wpjam_good_comments_admin_head');
function wpjam_good_comments_admin_head(){
    if(isset($_REQUEST['good_comment'])){
        if($_REQUEST['good_comment'] == '1'){
            add_comment_meta( $_REQUEST['comment_id'], 'good_comment', '1');
        }elseif($_REQUEST['good_comment'] == '0'){
            delete_comment_meta( $_REQUEST['comment_id'], 'good_comment');
        }
    }
}

function wpjam_get_good_comments(){

    $comments_query = new WP_Comment_Query;
    $comments = $comments_query->query( array( 'meta_key' => 'good_comment', 'meta_value' => '1', 'number' => 10 ) );

    if ( $comments ) {
        foreach ( $comments as $comment ) {
            $post = get_post($cooment->comment_post_ID);
            echo '

<li>
                '.get_avatar($comment->comment_ID,50).'
                <a href="'.get_permalink($comment->comment_post_ID).'" title="'. esc_attr(strip_tags($post->post_title)).'"><strong>@'.$comment->comment_author.'</strong>:'.get_comment_text($comment->comment_ID).'</a>
            </li>
';
        }
    }
}

将上面插件单独保存为一个插件,并上传激活,然后既可以使用 wpjam_get_good_comments 模板函数输出最新的10条好评了。


0 人点赞