BLOG

特定のカスタム投稿タイプのみ投稿数を取得する

| WordPress

カスタム投稿タイプを複数使っていてカスタムタクソノミー等を共有している場合にカウントが、複数分のカスタム投稿タイプの合計が取得されてしまいますよね。

例えば、事業所とスタッフというカスタム投稿タイプと、都道府県っていうタクソノミーがあってどっちの投稿タイプでも都道府県というタクソノミーを使っている場合、大阪のスタッフの数を取得したいのに事業所で登録している数も取得されてしまうようになるのです。

事業所 大阪 6個登録してある
スタッフ 大阪 10人登録してある

都道府県タクソノミーの大阪のタームの数を取得すると16という数字になってしまう

と、こんな感じになりますよね。
これを、大阪のスタッフで取得したいというのが今回の目的です。

というわけで調べてみたらfunctions.phpに以下を記載するだけでいけるみたいです。

// Handle the post_type parameter given in get_terms function
function df_terms_clauses($clauses, $taxonomy, $args) {
  if (!empty($args['post_type'])) {
    global $wpdb;

    $post_types = array();

    foreach($args['post_type'] as $cpt) {
      $post_types[] = "'".$cpt."'";
    }

    if(!empty($post_types)) {
      $clauses['fields'] = 'DISTINCT '.str_replace('tt.*', 'tt.term_taxonomy_id, tt.term_id, tt.taxonomy, tt.description, tt.parent', $clauses['fields']).', COUNT(t.term_id) AS count';
      $clauses['join'] .= ' INNER JOIN '.$wpdb->term_relationships.' AS r ON r.term_taxonomy_id = tt.term_taxonomy_id INNER JOIN '.$wpdb->posts.' AS p ON p.ID = r.object_id';
      $clauses['where'] .= ' AND p.post_type IN ('.implode(',', $post_types).')';
      $clauses['orderby'] = 'GROUP BY t.term_id '.$clauses['orderby'];
    }
  }
  return $clauses;
}
add_filter('terms_clauses', 'df_terms_clauses', 10, 3);

あとは普通にget_terms()で取得するだけです。

// Get the categories for post and product post types
$args = array(
  'post_type' => array('jigyosyo'),
  'hide_empty' => 0,
  'orderby' => 'name',
  'order'=>'ASC',
);
$categories = get_terms('todofuken', $args);

こんな感じです。
全部の取りたいときはpost_typeの指定をしなければいいです。

PAGE TOP