How to Pull Comments From a Specific Standalone Page in Typecho
If you want Typecho to fetch comments from a single standalone page and output them as <li> items, this snippet does the job nicely. I came across it online and saved it for later.
It can be used in fairly flexible ways too. For example, if you have a guestbook, links page, or even a timeline-style page, you could pull those comments onto the homepage and turn them into a scrolling notice area or some other small display block.
Here is the code:
<?php
$slug = "links"; //独立页面缩略名
$limit = 8; //调用评论数量
$length = 30; //截取文字长度
$ispage = true; //true 输出页面评论,false 输出其它所有评论
$isGuestbook = $ispage ? " = " : " <> ";
$db = $this->db;//Typecho_Db::get();
$options = $this->options;//Typecho_Widget::widget('Widget_Options');
$page = $db->fetchRow($db->select()->from('table.contents')
->where('table.contents.status = ?', 'publish')
->where('table.contents.created < ?', $options->gmtTime)
->where('table.contents.slug = ?', $slug));
if( $page ){
$type = $page['type'];
$routeExists = (NULL != Typecho_Router::get($type));
$page['pathinfo'] = $routeExists ? Typecho_Router::url($type, $page) : '#';
$page['permalink'] = Typecho_Common::url($page['pathinfo'], $options->index);
$comments = $db->fetchAll($db->select()->from('table.comments')
->where('table.comments.status = ?', 'approved')
->where('table.comments.created < ?', $options->gmtTime)
->where('table.comments.type = ?', 'comment')
->where('table.comments.cid '.$isGuestbook.' ?', $page['cid'])
->order('table.comments.created', Typecho_Db::SORT_DESC)
->limit($limit) );
foreach($comments AS $comment) {
echo '<li>';
echo '<a href="'. $page['permalink']."#comment-".$comment['coid'] .'" title="'.$comment['text'].'">';
echo Typecho_Common::subStr(strip_tags($comment['text']), 0, $length, '...').'</a>';
echo '</li>';
}
}else{
echo "<li>No Comments</li>";
}
?>
Just drop it wherever you want the list to appear.
The logic is straightforward:
- set the page slug with
$slug - control how many comments to show with
$limit - trim the displayed text with
$length - decide whether to pull comments only from that standalone page, or from everything else, with
$ispage
The script first looks up the target page in table.contents, builds its permalink, then queries table.comments for approved comments, sorts them by newest first, and loops through the results. What gets output in the end is a list of linked comment excerpts, each pointing directly to its corresponding comment anchor.
The code is a bit wordy as written, so you can trim it down if you only need the core part. Really, the heart of it is just one query plus one looped output.
Another practical option is to wrap this into a function, so you can call comments from different standalone pages in multiple places. The basic idea never changes: query the comment table, read the text field, loop through the results, and print them.