====解決した方法を記載します====
functions.phpに教えていただいたコードを指定するだけでは上手くいかず、時間がかかってしまいました。
私が上手くいった方法をメモしておきます。
結果的に、functions.phpに、関数を指定してphpに出力することで解決しました!
●ステップ1
ベストアンサーに選ばせていただいた参考URLにこの方のコードを追記しました
https://illbenet.jp/view/wordpress-get_terms_posttype
すると、カスタム投稿タイプに属するタクソノミーのタームだけを表示することができます。
ただ、この時点ではカウント数はタクソノミーが属する他のカスタム投稿の記事数もカウントされてしまいます。
ここで2週間ほど試行錯誤して沼にハマりました。
●ステップ2
こちらの方の記事を参考に、カウントする関数をfunctions.phpに作成したところ、思い通りの表示ができました!
https://teratail.com/questions/51990?sort=3
phpには下記のように記載しました。
カスタム投稿タイプのslug と カスタムタクソノミーのslugは、その都度変更します。
<?php echo getMyPostCount('カスタム投稿タイプのslug', 'カスタムタクソノミーのslug', $term->slug); ?>
かなりハマって時間が掛かってしまったので、
同じように悩んでいる方の参考になれば幸いです。
▼functions.php に追記したコード
// カスタム投稿タイプに属するタクソノミーのタームだけを表示
function df_terms_clauses($clauses, $taxonomy, $args)
{
if (isset($args['post_type']) && !empty($args['post_type']) && $args['fields'] !== 'count') {
global $wpdb;
$post_types = [];
if (is_array($args['post_type'])) {
foreach ($args['post_type'] as $cpt) {
$post_types[] = "'".$cpt."'";
}
} else {
$post_types[] = "'".$args['post_type']."'";
}
if (!empty($post_types)) {
$clauses['fields'] = 'DISTINCT '.str_replace('tt.*', 'tt.term_taxonomy_id, tt.taxonomy, tt.description, tt.parent', $clauses['fields']).', COUNT(p.post_type) AS count';
$clauses['join'] .= ' LEFT JOIN '.$wpdb->term_relationships.' AS r ON r.term_taxonomy_id = tt.term_taxonomy_id LEFT JOIN '.$wpdb->posts.' AS p ON p.ID = r.object_id';
$clauses['where'] .= 'AND p.post_status = "publish" AND (p.post_type IN ('.implode(',', $post_types).') OR p.post_type IS NULL)';
$clauses['orderby'] = 'GROUP BY t.term_id '.$clauses['orderby'];
}
}
return $clauses;
}
add_filter('terms_clauses', 'df_terms_clauses', 10, 3);
// 指定のカスタム投稿タイプとタクソノミー・タームに属する記事数を取得する関数
// この関数を使うと上手くいきました!
function getMyPostCount($post_type, $taxonomy, $terms)
{
$args = [
'post_type' => $post_type,
'tax_query' => [
[
'taxonomy' => $taxonomy,
'field' => 'slug',
'terms' => $terms,
],
],
];
$query = new WP_Query($args);
return $query->found_posts;
}
▼php に追記したコード
<?php if ($terms): ?>
<ul class="terms sp_display_f f_wrap">
<?php
$args = [
'post_type' => ['カスタム投稿タイプのslug'],
'hide_empty' => 0,
'orderby' => 'name',
'order' => 'ASC',
];
$terms = get_terms('price', $args);
?>
<?php foreach ($terms as $term): ?>
<li>
<input class="" type="checkbox" name="price[]" value="<?php echo esc_attr($term->slug); ?>">
<?php echo esc_html($term->name); ?>
(<?php echo getMyPostCount('カスタム投稿タイプのslug', 'カスタムタクソノミーのslug', $term->slug); ?>)
</li>
<?php endforeach; ?>
</ul>
<?php endif; ?>
バッドをするには、ログインかつ
こちらの条件を満たす必要があります。