不在选定类别中的帖子总数?

时间:2010-10-25 作者:RichZenMaster

我需要获得不在选定类别中的帖子总数。我有要从count中排除的类别的类别ID(在变量中$folio_cat_ids)

到目前为止,我有一个不起作用的代码,

$numposts = $wpdb->get_var("SELECT COUNT(*) FROM $wpdb->posts 
  WHERE post_status = \'publish\' 
    AND post_type = \'post\' 
    AND post_name NOT LIKE \'%revision%\' 
    AND post_name NOT LIKE \'%autosave%\' 
    AND post_category NOT IN($folio_cat_ids)");
请帮忙。

2 个回复
SO网友:Rarst

你的帖子有多个类别吗?如果没有-我认为各个类别的计数都会被缓存,因此可以将计数相加:

$categories = get_categories( array( \'exclude\' => $folio_cat_ids ) );

$count = 0;
foreach ( $categories as $category)
    $count += $category->category_count;
也可以只获取和统计帖子,这更灵活,可以处理重叠,但资源更密集:

$posts = get_posts( array(
    \'category__not_in\' => $folio_cat_ids,
    \'numberposts\' => \'-1\'
) );

$count = count( $posts );

SO网友:MikeSchinkel

你好@Rich:

欢迎使用WordPress答案。

这个\'post_category\' 字段不再使用,已被一组“分类法”表所取代。如果您使用的是direct SQL,则如下所示:

$sql = <<<SQL
SELECT 
  COUNT(*) 
FROM 
  {$wpdb->posts} 
  INNER JOIN {$wpdb->term_relationships} ON {$wpdb->term_relationships}.object_id={$wpdb->posts}.ID
  INNER JOIN {$wpdb->term_taxonomy} ON {$wpdb->term_taxonomy}.term_taxonomy_id={$wpdb->term_relationships}.term_taxonomy_id
WHERE 1=1
  AND {$wpdb->posts}.post_status = \'publish\' 
  AND {$wpdb->posts}.post_type = \'post\' 
  AND {$wpdb->posts}.post_name NOT LIKE \'%revision%\' 
  AND {$wpdb->posts}.post_name NOT LIKE \'%autosave%\' 
  AND {$wpdb->term_taxonomy}.term_id NOT IN ($folio_cat_ids)
SQL;
$numposts = $wpdb->get_var($sql);
然而,如果可以避免在使用WordPress API时编写大量SQL,那么最好使用WordPress API而不是直接SQL,在这种情况下,这是非常可能的。我为你写了一个小班叫CountPostsCategoriesNotIn 它封装了\'posts_fields\' 您需要使用的挂钩。调用此类非常简单:

$folio_cat_ids = \'1,2,3\';
$numposts = CountPostsCategoriesNotIn::count($folio_cat_ids);
echo "$numposts\\n";
这是一个可以复制到主题中的类functions.php 文件或在中使用.php 您可能正在编写的插件的文件:

class CountPostsCategoriesNotIn {
  static function count($categories) {
    $posts_fields = array(__CLASS__,\'posts_fields\');
    add_action(\'posts_fields\',$posts_fields);
    $query = new WP_Query(array(
      \'posts_per_page\' => \'-1\',
      \'category__not_in\' => $categories,
    ));
    remove_action(\'posts_fields\',$posts_fields);
    return $query->post->post_count;
  }
  static function posts_fields($field_list) {
    $field_list = \'COUNT(*) as post_count\';
    return $field_list;
  }
}

结束

相关推荐