自定义查询num_row返回错误的金额

时间:2011-11-22 作者:Sweepster

因此,我有一个自定义查询,可以获取给定类别中的所有帖子。我试图获得返回的行数,但它给了我错误的数字。

我得到的不是11个,而是14个。有人知道为什么吗?

<?php
$pageposts = $wpdb->get_results($wpdb->prepare("
    SELECT * FROM $wpdb->posts
    LEFT JOIN userContests ON ($wpdb->posts.ID = userContests.contestID)
    LEFT JOIN $wpdb->term_relationships ON ($wpdb->posts.ID = $wpdb->term_relationships.object_id)
    LEFT JOIN $wpdb->term_taxonomy ON ($wpdb->term_relationships.term_taxonomy_id = $wpdb->term_taxonomy.term_taxonomy_id)
    WHERE $wpdb->posts.post_status = \'publish\' 
    AND $wpdb->posts.post_type = \'post\' 
    AND $wpdb->posts.post_date < NOW() 
    AND $wpdb->term_taxonomy.taxonomy = \'category\'
    AND $wpdb->term_taxonomy.term_id IN(3)
    ORDER BY $wpdb->posts.post_date DESC
    "), OBJECT);

/*   $rows = $wpdb->num_rows;  <------ Wrongly returns 14 */

/*   $rows = $wpdb->get_var($wpdb->prepare("      <--------- Correctly returns 11
        SELECT COUNT(*) FROM $wpdb->posts
        LEFT JOIN userContests ON ($wpdb->posts.ID = userContests.contestID)
        LEFT JOIN $wpdb->term_relationships ON ($wpdb->posts.ID = $wpdb->term_relationships.object_id)
        LEFT JOIN $wpdb->term_taxonomy ON ($wpdb->term_relationships.term_taxonomy_id = $wpdb->term_taxonomy.term_taxonomy_id)
        WHERE $wpdb->posts.post_status = \'publish\' 
        AND $wpdb->posts.post_type = \'post\' 
        AND $wpdb->posts.post_date < NOW() 
        AND $wpdb->term_taxonomy.taxonomy = \'category\'
        AND $wpdb->term_taxonomy.term_id IN(3)
        ORDER BY $wpdb->posts.post_date DESC")); */
echo "Number of rows = " .$rows;
?>
我的工作似乎是在浪费资源。有没有更有效的方法?

1 个回复
SO网友:Joshua Abenazer

如果你想知道某个特定类别中所有已发布帖子的总数,你可以试试这个。

$all_posts = new WP_Query( array( \'posts_per_page\' => -1, \'post_status\' => \'publish\', \'cat\' => 3 ) );
echo $all_posts->post_count;

$all_posts = new WP_Query( array( \'posts_per_page\' => -1, \'post_status\' => \'publish\', \'category_name\' => \'uncategorized\' ) );
echo $all_posts->post_count;
只需确保将“category\\u name”或“cat”替换为所需的类别即可。

结束