LoginSignup
1
1

More than 5 years have passed since last update.

[WordPress] ターム(カテゴリー・タグ)の記事が指定件数以下なら一覧などに出力しない

Last updated at Posted at 2018-01-31

「[WordPress] ターム(カテゴリー・タグ)アーカイブで記事が指定件数以下なら404扱いにしたい」
https://qiita.com/gatespace/items/a29b0814a308fa2d77d7

上記でアーカイブページを404にしたのだけど、投稿ページ(single.php)カテゴリーやタグの一覧や、ウィジェットのカテゴリーやタグクラウドなど、とにかくリンク自体も出したくない場合。

投稿に関する場合

the_category(), the_tags(), the_terms() など最終的には get_the_terms() で呼び出してるので大元のフィルターフックで改変。
https://developer.wordpress.org/reference/functions/get_the_terms/

my_get_the_terms.php
<?php
// get_the_terms でタグに所属する投稿が指定した件数より少なかったら表示しない
add_filter( 'get_the_terms', 'my_get_the_terms', 10, 3 );
function my_get_the_terms( $terms, $post_id, $taxonomy ) {
    if ( is_admin() ) { // 管理画面だったら何もしない
        return $terms;
    }
    if ( $taxonomy != 'post_tag') { // 条件分岐はよしなに
        return $terms;
    }

    $new_terms = array();
    foreach ( $terms as $term ) {
        if ( $term->count >= 6 ) {
            $new_terms[] = $term;
        }
    }
    return $new_terms;
}

投稿に関係ないタームの一覧の場合

ウィジェットの「カテゴリー」や「タグクラウド」などなど、タームに関するものはget_terms() で呼び出してるので大元のフィルターフックで改変。
https://developer.wordpress.org/reference/functions/get_terms/

なお、4.5.0以降は get_terms() のパラメーターでタクソノミーの渡し方が変わってるので注意。

my_get_terms.php
<?php
// get_terms でタグに所属する投稿が指定した件数より少なかったら表示しない
add_filter( 'get_terms', 'my_get_terms', 10, 4 );
function my_get_terms( $terms, $taxonomies, $args, $term_query ) {
    if ( is_admin() ) { // 管理画面だったら何もしない
        return $terms;
    }
    if ( $taxonomies[0] != 'post_tag' ) { // 条件分岐はよしなに
        return $terms;
    }
    $new_terms = array();
    foreach ( $terms as $term ) {
        if ( $term->count >= 6 ) {
            $new_terms[] = $term;
        }
    }
    return $new_terms;
}

Advanced Custom Fields のタクソノミーフィールドの場合

https://www.advancedcustomfields.com/resources/taxonomy/
Objectsにしていた場合は $term->count で記事数が取れるのでよしなに条件分岐で弾いてください。
(IDの場合はしちめんどくさいので)

現場からは以上です。

1
1
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
1
1