2016-04-29 9 views
0

特定のタグが含まれている記事でカテゴリを取得し、Aは、B、C、Dは、など私たちは、10個のカテゴリーがあり

我々は、get_categoriesが持っているすべてのカテゴリを取得しますtag

機能1個のタグを言っていると言います(デフォルトでは)投稿がありますが、必要なのは同じ機能です。特定のタグを持つ投稿のあるカテゴリのみを取得する必要があります。

だから、カテゴリAタグtagと5つのポストがあり、カテゴリーBはカテゴリーC 3.その後、私はこのリストにACを見たいと思っており、どれを持っていません。

get_categoriesをタグでフィルタリングすることはできますか?

$terms = get_terms(array(
      'taxonomy' => 'category', 
      'hide_empty' => true, 
      'meta_query' => array(
       array(
        'key'  => 'tag', 
        'value' => 'my-tag-slug', 
        'compare' => '=', 
       ), 
      ), 
     )); 

しようとしたアップデート1

はまた、タグのIDで試してみました。これは私が使用している標準の投稿カテゴリとタグです。

答えて

1

使用get_terms()の代わりに、あなたが使用することができますmeta_queryの引数を利用します。これは、使用しているワードプレスのバージョンによって異なりん

$terms = get_terms(array(
    'taxonomy' => 'category', 
    'hide_empty' => true, 
    'meta_query' => array(
     array(
      'key'  => 'tag', 
      'value' => 'tag', 
      'compare' => '=', 
     ), 
    ), 
)); 

- ので、ご確認ください:ようhttps://developer.wordpress.org/reference/functions/get_terms/

何かドキュメンテーション

引数の 'meta_query'部分については、https://codex.wordpress.org/Class_Reference/WP_Queryを参照してください。

UPDATE

// Get the categories 
$terms = get_terms(array(
    'taxonomy' => 'category', 
)); 

// Loop through them 
foreach($terms as $term) { 
    // Get the posts in that category with the required tag 
    $args = array(
    'category_name' => $term->name, 
    'tax_query'  => array(
     array(
      'taxonomy' => 'post_tag', 
      'field'  => 'slug', 
      'terms'  => '{tag-slug}' 
     ) 
    ) 
); 
    $posts_array = get_posts($args); 

    foreach ($posts_array as $value) { 
    // save what you need here - maybe an array for each category with the posts so you can run a count on them? 
    } 

} 
+0

おかげで、私はそれを試してみたが、動作していないようご必要なタグスラグに、この(ノートの変更{タグスラグ}のようなものを試してみてください私は空の配列を取得しています。私は4.5.1上にありますので、コードは問題ありません。https://codex.wordpress.org/Class_Reference/WP_Meta_QueryまたはGoogle以外でもタグに関連するものは見つかりません。 。 – Richard

+0

私の質問が更新されました – Richard

+0

自分のバージョンのコードを表示できますか?カテゴリとメタ名が何であるか分かります。そのままコピーして貼り付けるとうまくいきます。 –

関連する問題