WordPressでサイドバーに独自の新着コメントをリストを追加
ウィジェットを使えば新着コメントをサイドバーに出す事は可能ですが、デフォルトのHTMLだとカスマイズしにくい場合がります。
その時は以下のソースをサイドバーに追加する事で独自の新着コメントリストを表示できます。これならHTMLも編集できるのでCSSカスタマイズもやりやすくなります。
<ul id="new-comments">
<?php
$comments = get_comments('type=comment&status=approve&number=10');
$output = '';
if(is_array($comments) && count($comments) == 0) echo "コメントはありません。";
//コメントがある場合
else{
//コメントを記事ごとにまとめる
foreach($comments as $comment){
isset($posts_list[$comment->comment_post_ID])? $posts_list[$comment->comment_post_ID]++ : $posts_list[$comment->comment_post_ID] = 1;
}
while(list($key, $val) = each($posts_list)){
$first_comment = true;
foreach($comments as $comment){
$author = "匿名";
if($comment->comment_post_ID != $key) continue;
if($first_comment){
//記事タイトル取得
$comment_post = get_post($comment->comment_post_ID);
$post_title = mb_strimwidth($comment_post->post_title, 0, 40, "...", "UTF-8");
$permalink = get_permalink($comment->comment_post_ID)."#comments";
$output .= "<li><a href=\"$permalink\">$post_title</a>\n";
$output .= "\t<ul>\n";
$first_comment = false;
}
$commentid = get_permalink($comment->comment_post_ID)."#comment-".$comment->comment_ID;
if(mysql2date('Ymd', $comment->comment_date)== date_i18n('Ymd')) $comment_date = mysql2date('H:i', $comment->comment_date);
elseif(mysql2date('Y', $comment->comment_date)== date_i18n('Y')) $comment_date = mysql2date('m/d', $comment->comment_date);
else $comment_date = mysql2date('Y/m/d', $comment->comment_date);
if($comment->comment_author) $author = mb_strimwidth($comment->comment_author, 0, 30, "...", "UTF-8");
$output .= "\t\t<li><span class=\"comment_author\"><a href=\"$commentid\" title=\"\">".$author."</a> </span>".
"<span class=\"comment_date\">( $comment_date )</span></li>\n";
}
$output .= "\t</ul>\n</li>\n";
}
echo $output;
} ?>
</ul>
表示される時は以下のようになります。
・投稿記事タイトル
コメント者名(投稿日時)
コメント者名(投稿日時)



コメント入力欄