WordPress获取最新评论WP_Comment_Query()方法

通过WP_Comment_Query()方法获取

1
2
3
4
5
6
7
8
9
10
11
12
13
14
function bg_recent_comments($no_comments = 5, $comment_len = 80, $avatar_size = 48) {
    $comments_query = new WP_Comment_Query();
    $comments = $comments_query->query( array( 'number' => $no_comments ) );
    $comm = '';
    if ( $comments ) : foreach ( $comments as $comment ) :
        $comm .= '<li><a class="author" href="' . get_permalink( $comment->comment_post_ID ) . '#comment-' . $comment->comment_ID . '">';
        $comm .= get_avatar( $comment->comment_author_email, $avatar_size );
        $comm .= get_comment_author( $comment->comment_ID ) . ':</a> ';
        $comm .= '<p>' . strip_tags( substr( apply_filters( 'get_comment_text', $comment->comment_content ), 0, $comment_len ) ) . '...</p></li>';
    endforeach; else :
        $comm .= 'No comments.';
    endif;
    echo $comm;
}
1
2
3
4
<div class="widget recent-comments">
    <h3>Recent Comments</h3>
    <?php bg_recent_comments(); ?>
</div>
1
2
3
4
5
.recent-comments { list-style: none; font-size: 12px; color: #485358; }
.recent-comments li { overflow: hidden; padding: 20px 0; border-top: 1px dotted #DADEE1; }
.recent-comments li:first-child { border: 0 none; }
.recent-comments img { float: left; margin-right: 8px; }
.recent-comments a { display: block; margin-top: 10px; padding-top: 10px; text-transform: uppercase; }

通过自定义SQL获取

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
<?php //Get Recet Comments Function
function get_recent_comments($no_comments = 10, $comment_len = 35) {

   global $wpdb;

    $request  = "SELECT * FROM $wpdb->comments";
    $request .= " JOIN $wpdb->posts ON ID = comment_post_ID";
    $request .= " WHERE comment_approved = '1' AND post_status = 'publish' AND post_password =''";
    $request .= " ORDER BY comment_date DESC LIMIT $no_comments";

    $comments = $wpdb->get_results($request);

    if ($comments) {
        foreach ($comments as $comment) {
            ob_start();
            ?>
                <li>
                    <a href="<?php echo get_permalink( $comment->comment_post_ID ) . '#comment-' . $comment->comment_ID; ?>"><?php echo dp_get_author($comment); ?>:</a>
                    <?php echo strip_tags(substr(apply_filters('get_comment_text', $comment->comment_content), 0, $comment_len)); ?>
                </li>
            <?php
            ob_end_flush();
        }
    } else {
        echo '<li>'.__('No comments', 'banago').'</li>';
    }
}

function dp_get_author($comment) {
    $author = "";

    if ( empty($comment->comment_author) )
        $author = __('Anonymous', 'banago');
    else
        $author = $comment->comment_author;

    return $author;
}
原文链接:https://xiaohost.com/3719.html,转载请注明出处。
0

评论0

请先