如何拆分Wordpress查询


How do I Split Up A Wordpress Query?

我在网上到处找,甚至试图雇佣一名自由职业者来寻求帮助,但没有成功。在搜索时,我发现了如何在wordpress中从选定的类别中获得热门帖子&http://www.queness.com/code-snippet/6546/how-to-display-most-popular-posts-from-a-specific-category-in-wordpress这基本上就是我想要的,但我想把我从中得到的信息分开,这样我就可以对帖子进行排名。

<?php
$args=array(
  'cat' => 3, // this is category ID
  'orderby' => 'comment_count',
  'order' => 'DESC',
  'post_type' => 'post',
  'post_status' => 'publish',
  'posts_per_page' => 6, // how much post you want to display
  'caller_get_posts'=> 1
);
$my_query = null;
$my_query = new WP_Query($args);
if( $my_query->have_posts() ) { ?>
<ul>
<?php while ($my_query->have_posts()) : $my_query->the_post(); ?>
<li><a href="<?php the_permalink() ?>" rel="bookmark" title="Permanent Link to <?php    the_title_attribute(); ?>"><?php the_title(); ?></a></li>
<?php  endwhile; ?>
</ul>
<?php }
wp_reset_query(); ?>

有了这段代码,它获得了最受欢迎的评论帖子,我想做的基本上是获取结果并添加排名,就像下面的例子一样。

#1 - post 1
#2 - post 2
#3 - post 3
#4 - post 4
#5 - post5 last post

提前感谢的任何帮助

也许这个想法会对你有所帮助。

使用get_comments_number($post_id)函数

获取评论数量,然后执行if-else循环以显示排名。

$num_comments = get_comments_number(); // get_comments_number returns only a numeric value
if ( comments_open() ) {
if ( $num_comments == 0 ) {
    $rating= 0 ;
} elseif ( $num_comments > 1 ) {
    $rating= 1 ;
} else {
    $rating= 0 ;
}
}

感谢

根据您当前的问题,我理解以下内容:

  1. 您想从WP数据库中查询评论最多的帖子
  2. 您希望向访问者显示已收到帖子的排名。排名由帖子的评论量决定

所以你的结果可能是:

1篇文章A(评论数500)

2帖子B(评论数499)

3 Post Z(评论计数200)

我会这样做:

<?php
function get_popular_posts()
{
$sql="SELECT comment_count, guid AS link_to_post, post_title
FROM wp_posts 
WHERE post_status = "publish" AND post_type = "post"
ORDER BY comment_count DESC
LIMIT 5"
return $wpdb->get_results($sql, OBJECT)
}   
$post_objects = get_popular_posts();
$i = 1;
foreach($post_objects as $object)
{
echo 'Post: ' . $i . '#' . ' ' . $post_title . ' ' . $link_to_post . ' ' . $comment_count;
$i++;
}
?>

尚未测试代码。但它应该从数据库中提取五个"顶级职位"。由于解释原因,留在了comment_count中。