【发布时间】:2012-07-24 12:24:47
【问题描述】:
我试图在侧边栏中仅显示当前类别的 cmets。到目前为止,我得到了这个:
但它不起作用,它要么到处显示 0 cmets,要么到处都显示。我不明白我做错了什么......
问题似乎是这部分: // 类别(可以是父类别) $cat = get_query_var('cat'); $category_parent = $cat;
<?php
// Posts per page setting
$ppp = 8; //get_option('posts_per_page'); // either use the WordPress global Posts per page setting or set a custom one like $ppp = 10;
$custom_offset = 0; // If you are dealing with your custom pagination, then you can calculate the value of this offset using a formula
// category (can be a parent category)
$cat = get_query_var('cat');
$category_parent = $cat;
// lets fetch sub categories of this category and build an array
$categories = get_terms( 'category', array( 'child_of' => $category_parent, 'hide_empty' => false ) );
$category_list = array( $category_parent );
foreach( $categories as $term ) {
$category_list[] = (int) $term->term_id;
}
// fetch posts in all those categories
$posts = get_objects_in_term( $category_list, 'category' );
$sql = "SELECT comment_ID, comment_date, comment_content, comment_post_ID, user_id, comment_author
FROM {$wpdb->comments} WHERE
comment_post_ID in (".implode(',', $posts).") AND comment_approved = 1
ORDER by comment_date DESC LIMIT $ppp OFFSET $custom_offset";
$comments_list = $wpdb->get_results( $sql );
if ( count( $comments_list ) > 0 ) {
$date_format = get_option( 'date_format' );
foreach ( $comments_list as $comment ) {
?>
<li>
<a href="<?php echo ( get_permalink( $comment->comment_post_ID ) ); ?>#comment-<?php echo($comment->comment_ID); ?>"><?php echo get_avatar( $comment->user_id, 50 ); ?></a>
<span><strong><?php echo($comment->comment_author); ?></strong> commented on</span>
<h3><a href="<?php echo ( get_permalink( $comment->comment_post_ID ) ); ?>"><?php echo get_the_title ( $comment->comment_post_ID ); ?></a></h3>
<span><?php echo($comment->comment_date); ?></span>
<p>"<?php comment_excerpt(); ?>" <a href="<?php echo ( get_permalink( $comment->comment_post_ID ) ); ?>#comment-<?php echo($comment->comment_ID); ?>">Read More</a></p>
<div class="clearfloat"></div><!-- Very Important -->
</li>
<?php
}
} else {
echo '<p>No comments</p>';
}
?>
【问题讨论】:
-
我不太明白“它要么到处显示 0 cmets,要么到处都显示 0 cmets”。两个注意事项:1)您的 SQL 查询将获取“所有批准的 cmets”(是否有任何批准?) 2)您的 HTML 输出是
- 元素。这些是在父
- 元素下呈现的吗?
- 元素。这些是在父
-
@pankar 是的,他们在父级 ul 下。
-
@pankar 至于另一个问题,我在这里找到了这个脚本:blog.ashfame.com/2011/04/get-comments-category-wordpress 这是我认为的第三个例子。我改变了 $category_parent = 3;到 $category_parent = $cat;所以理论上脚本应该只从 $cat 类别 cmets 中获取。
-
@pankar 如果我输入 $category_parent = 644;这是包含 4 个 cmets 的类别 ID,我总共显示了 6 个 cmets。如果我把没有 cmets 的 645 显示为 0 cmets。
-
ID=644 的类别是否有任何“子”类别又具有 cmets?我这么说是因为上面的代码会从父类中获取所有的 cmets,包括它的子类