0
1

More than 3 years have passed since last update.

wordpress タクソノミー とカスタムフィールドのちょっと便利な話

Posted at

記事を書いた時の各バージョンです。
wordprss 5.3.2
acf pro 5.8.9

こんなシーン

wordpressカスタム投稿と一緒に、カスタムタクソノミーを設定する際に、それぞれのタームに連動したカスタムフィールドが欲しい・・・。

例えば
・タームごとにアイコンを出力したい。
・タームごとに独自の(slugとは別の)クラスを付与したい。
・日本語名に対する、他言語翻訳を同時に設定したい。

やりようはいくらでもあるかと思いますが、タームに連動したカスタムフィールドを追加することでよりスマートに実現できます。
しかし、値の取得は通常のカスタムフィールドとは手順が異なります。

タクソノミー実装

ひとまずこんなかんじでしょうか。

tax.php
add_action('init', 'register_cf');
function register_cf()
{
  register_post_type(
    news,
    array(
      'labels' => array(
        'name' => __('NEWS'),
        'singular_name' => __('NEWS'), // 以下略
      ),
      'has_archive' => true,
      'public' => true,
    )
  );

  register_taxonomy(
    news_tag,
    news,
    array(
      'labels' => array(
        'name' => __('タグ'),
        'singular_name' => __('タグ'), // 以下略
      ),
      'public' => true,
    )
  );
}

カスタム投稿(news)にカテゴリー(news_tag)が設定されます。
あとは、acfのフィールド追加画面「位置」でタクソノミー 等しい カテゴリー(news_tag)が選択できるので、選択します。
ターム設定画面にフィールドが追加されていたら成功です。

値の取得

今回は、newsに「政治」というタームを追加したとします。
カスタムフィールドに英語訳「politics」を指定して、値を取得します。
(カスタムフィールド名は「en_tag」とします。)

tag.php
// 前後の記述は省略します。

$taxs = get_the_terms($post->ID, 'news_tag');
foreach ($taxs as $tax) {
 // タームのID取得
 $id = esc_html($term->$term_id);
 $idsp = 'news_tag_'.$id;
 // IDに基づいたカスタムフィールドの取得
 echo get_field('en_tag', $idsp);
}

// 前後の記述は省略します。

上記の例だと、他言語サイトにおいてタクソノミーの管理がしやすくなるので、便利です。

0
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
0
1