Advanced Custom Fields表示タグ

Advanced Custom Fields-フィールドタイプ

サイトに表示させるために、タグをテンプレートに埋め込みます。

私は、/wp-content/themes/sample/page-templates/
にあるテンプレートをコピーして任意の名前で同フォルダ内に保存。
それを会社概要のテンプレートとして、以下のタグを入れました。


会社名:<?php echo post_custom(‘comp1‘); ?>
電話番号:<?php echo post_custom(‘comp2‘); ?>
住所:<?php echo post_custom(‘comp3‘); ?>
地図:<img src=”<?php the_field( ‘comp4‘,$post->ID); ?>” alt=”" />
一言:<?php echo post_custom(‘comp5‘); ?>


サンプル /foct.jp/wp-sample/wp-content/themes/sample/page-templates/comp.php

緑字の部分はフィールドタイプです。
青字は、さっきつけたフィールド名です。
画像のタグは選んだ「返り値」によって違います。 ※下に一覧を入れておきました。

 

カスタムフィールドの値でページの表示内容を切り替えたいときってあります。

例えば、商品なんかでsoldoutというチェックのカスタムフィールドを作った時、ここにチェックを入れたら表示に「売切れ」と出す、とかね。

これはあくまでテンプレートのデータをカスタムするとき。

、カスタムフィールドに値が入っているかどうかで表示を切り替える。

<?php if(get_post_meta($post->ID,'フィールド名',true)): ?>
コンテンツを表示する
<?php endif; ?>

、カスタムフィールドの値によって表示を変更したいとき

<?php if(get_post_meta($post->ID,'フィールド名',true) == 'フィールドの値'): ?>
コンテンツを表示する
<?php endif; ?>

でOKです!

 

他にもフィールドタイプはたくさんあります。

  • Text Field
  • Number Field
  • Textarea Field
  • Wysiwyg Editor Field
  • Image Field
  • File Field
  • Select Field
  • Checkbox Field
  • True / False Field
  • Radio Field
  • Date Picker Field
  • Color Picker Field
  • Relationship Field
  • Page Link Field
  • Post Object Field

 

 

Text Field は、単一行のテキストを入力できます。

URL や E-mail かをチェックするバリデーション機能はありません。

フィールド定義時のオプション

フィールドの値に HTML を含むときの動作を指定できます。

・無:HTML タグとして認識せず、文字列としてそのまま吐き出します。

・HTML:HTML タグとして認識します。

フォーマット

フィールド入力

Text

フィールド出力
〒<?php the_field('zip_code',$post->ID); ?>

Number Field は、単一行のテキストを入力できます。

数字以外の入力があると、保存時にエラーも出さずに数字以外を無視して保存します。

フィールド入力

右側の▲/▼をクリックすると数値が 1 ずつ増減します。

Number Field

フィールド出力
<?php
$uriage = get_field('uriage',$post->ID);
echo number_format($uriage);
?>

Textarea Field は、複数行のテキストを入力できます。

フィールド定義のオプション

改行の扱いはフィールド設定時に決めることができます。

フォーマット

フィールド入力

Text Area

フィールド出力
<!-- 改行指定をしたとき -->
<p><?php the_field('memo',$post->ID); ?></p>
<!-- 改行指定をしなかったとき -->
<p><?php echo nl2br(get_field('memo',$post->ID)); ?></p>

Wysiwyg Editor Field は、TinyMCE でテキストを入力できます。

フィールド定義時のオプション

ツールバーの形態やアップロードボタンの有無を選択できます。

acf-wysiwyg

フィールド入力

フィールド出力
<?php the_field('other',$post->ID); ?>

Image Field は、画像をアップロードできるインターフェイスを提供します。

アップロードした画像は、ポストの添付画像として管理されます。

フィールド定義のオプション

カスタムフィールドに保存する値は、画像オブジェクト、画像 URL、画像 ID から選択できます。

acf-image-type

フィールド入力

Image Field

フィールド出力
<!-- 画像オブジェクトを設定した場合 -->
<?php
$attachment_obj = get_field('photo',$post->ID);
echo wp_get_attachment_image( $attachment_obj->ID, "full" );
?>

<!-- 画像 URL を設定した場合 -->
<img src="<?php the_field( 'photo',$post->ID); ?>" alt="" />

<!-- 画像 ID を設定した場合 -->
<?php
$attachment_id = get_field('photo',$post->ID);
echo wp_get_attachment_image( $attachment_id, "full" );
?>

<!-- 画像 ID を設定した場合 -->
<?php
$attachment_id = get_field('photo',$post->ID);
$image_attributes = wp_get_attachment_image_src($attachment_id);
$url = $image_attributes[0];$w = round($image_attributes[1] / 2); // 実寸の半分
$h = round($image_attributes[2] / 2); // 実寸の半分
$alt = get_post_meta($attachment_id, '_wp_attachment_image_alt', true);
?>
<img src="<?php echo $url; ?>" width="<?php echo $w; ?>" height="<?php echo $h; ?>" alt="<?php echo $alt; ?>" />

File Field は、ファイルをアップロードできるインターフェイスを提供します。

フィールド定義時のオプション

カスタムフィールドとして保存する値は、ファイルオブジェクト / ファイルURL / ファイルID から選択できます。

acf-file

フィールド入力

File Field

フィールド出力
<!-- URL を設定した場合 -->
<a href="<?php the_field('file',$post->ID); ?>">ダウンロード</a>

Select Field は、フィールド設定時に登録した項目をドロップダウンリストから選択できます。

フィールド定義時のオプション

選択オプションやデフォルト値の他に、単一選択か複数選択かを選べます。

acf-select

フィールド入力

select

フィールド出力
<!-- 単一選択のとき -->
<p>都道府県:<?php the_field('prefecture',$post->ID); ?></p>
<!-- 複数選択のとき -->
<p>都道府県:<?php echo implode(', ', get_field('prefecture',$post->ID)); ?></p>
<p>都道府県:
<?php
$prefectures = get_field('nation',$post->ID);
$n = 0;
foreach ($prefectures as $prefecture) :
   if ($n==0) echo $prefecture;
   else       echo ', '.$prefecture;
    $n++;
endforeach;
?>
</p>

<!-- if 文 単一選択のとき -->
<?php
if(get_field('prefecture',$post->ID) == "東京都") :
    //...
    endif;
    ?>

<!-- if 文 複数選択のとき -->
<?php
if( in_array('北海道',get_field('prefecture',$post->ID))) :
    //...
    endif;
    ?>

Checkbox Field は、フィールド設定時に登録した項目を複数を選択できます。

フィールド定義時のオプション

選択肢を入力します。

acf-checkbox

フィールド入力

フィールド出力
<!-- 日本にチェックがあるかの判断 -->
<?php if (in_array('日本', get_field('nation',$post->ID))) : ?>
    <p>日本にチェックがあります。</p>
    <?php endif; ?>

<!-- 日本とアメリカ合衆国の両方にチェックがあるかの判断 --><?php
$nations = get_field('nation',$post->ID);
if (in_array('日本', $nations) && in_array('アメリカ合衆国', $nations)) :
?>
    <p>日本とアメリカ合衆国の両方にチェックがあります。</p>
<?php endif; ?>

<!-- カンマ区切りで出力 -->
<p>国:<?php the_field('nation',$post->ID); ?></p>

<!-- カンマ区切り以外で出力 -->
<p>国:<?php echo implode(' ', get_field('nation',$post->ID)); ?></p>
<p>国:
<?php
$nations = get_field('nation',$post->ID);
$n = 0;
foreach ($nations as $nation) :
    if ($n==0) echo $nation;
        else       echo ' '.$nation;
    $n++;
    endforeach;
?>
</p>

True/False Fieldは、一つだけのチェックボックスを作成します。

ON = True , Off = false の値を持つ簡易版チェックボックスフィールドです。

フィールド定義時のオプション

tf-message

フィールド入力

true-false

フィールド出力
<?php
if (get_field('company_info',$post->ID)==true) : // 会社データなし
    echo '<p>この会社の情報は登録されていません。</p>';
else :
    //
    // 会社の情報を表示
    //
endif;

Radio Field は、フィールド設定時に登録た項目を一つだけ選択することができます。

フィールド定義時のオプション

acf-radio

フィールド入力

Radio Button Field

フィールド出力
<p>色:<?php the_field('color',$post->ID); ?></p>

Date Picker Field は、日付をテキストかカレンダーで入力できるインターフェイスを提供します。

フィールド定義時のオプション

保存と表示のフォーマットを指定します。

acf-date

フィールド入力

日付ピッカー

フィールド出力
<p>誕生日:<?php the_field('birthday',$post->ID); ?></p>
<?php
/*
*  Create PHP DateTime object from Date Piker Value
*  this example expects the value to be saved in the format: yy_mm_dd (JS) = Y_m_d (PHP)
*/
$date = DateTime::createFromFormat('Y_m_d', get_field('date_picker',$post->ID));
echo $date->format('d-m-Y');
?>

Color Picker Field は、色をテキストかカラーピッカーで入力できるインターフェイスを提供します。

フィールド定義時のオプション

デフォルト色を設定できます。

acf-color

フィールド入力

Color Picker

フィールド出力
<div id='box' style="background-color:<?php the_field('b_color',$post->ID); ?>">
    :
    </div>

Relationship Field は、関連するポストをセレクションから複数選択できます。

フィールド定義時のオプション

フィールド入力画面で選択する関係ポストを、投稿タイプやタームで絞り込んでおくことができます。

ポストのフィルター

フィールド入力

選択したポスト(右側のポスト)は Drag & Drop で順序を決めることができます。

relationship

フィールド出力
<?php
$my_posts = get_field('relationship',$post->ID);
if( $my_posts ):
  echo '<ul>'.PHP_EOL;
    foreach( $my_posts as $post) :
        setup_postdata($post);
?>
    <li>
      <a href="<?php the_permalink(); ?>"><?php the_title(); ?></a>
    </li>
<?php
endforeach;
echo '</ul>'.PHP_EOL;
  wp_reset_postdata();
endif;
?>
Relationship Field を使えば、Page Link Field は必要なし。
Relationship Field を使えば、Post Object Field は必要なし。

共通オプション

オプション 解説
フィールドの説明 ポスト編集画面のフィールドの説明として表示されます。
必須か? 必須入力のフィールドに指定します。
デフォルト値 フィールドの初期設定値を入力します。
Conditional Logic フィールドを表示するかどうかの条件を指定します。条件は、同じフィールドグループ内で定義した

  • select
  • checkbox
  • radio
  • true / false

で指定できます。これらのフィールドの AND 演算 / OR 演算も指定できます。

フィールド定義時のオプション

例えば、「職業」を選択するラジオボタンがあり、
「その他」を選択したときだけ「その他」の Text Field に職業を入力したいことはよくあります。

conditional

フィールド入力

Radio で「その他」以外の職業を選択した場合、Text Field「その他」は表示されません。

select-other

API 関数

get_field() , the_field() の他にも利用できる関数があります。

フィールドタイプ 解説
the_field() WordPress 標準の the_****() と同じで、関数内で値を表示します。
$post_id を省略するとグローバル変数 $post の ID の指定があったものとします。

<?php
the_field($field_name, $post_id);
// $post_id は、ポストの ID とは限りません。
$post_id = null; // current post
$post_id = 1;
$post_id = "option";
$post_id = "options"; // same as above
$post_id = "category_2"; // save to a specific category
$post_id = "event_3"; // save to a specific taxonomy (this tax is called "event")
$post_id = "user_1"; // save to user (user id = 1)
?>
get_field() これも WordPress 標準の get_****() と同じで、カスタムフィールドの値を返します。
返ってくる値は、フィールドタイプの設定によりマチマチです。
$post_id を省略するとグローバル変数 $post の ID の指定があったものとします。

<?php
echo get_field($field_name, $post_id);
// $post_id は、ポストの ID とは限りません。
$post_id = null; // current post
$post_id = 1;
$post_id = "option";
$post_id = "options"; // same as above
$post_id = "category_2"; // save to a specific category
$post_id = "event_3"; // save to a specific taxonomy (this tax is called "event")
$post_id = "user_1"; // save to user (user id = 1)
?>
has_sub_field() アドオン Repeater Field 用の関数

<?php
if ( get_field('repeater') ):
  while( has_sub_field('repeater') ):
  ?>
      <div>
          <img src="<?php the_sub_field('image'); ?>" alt="<?php the_sub_field('alt'); ?>" />
              <p><?php the_sub_field('content'); ?></p>
    </div>
  <?php endwhile; ?>
  <?php endif;
the_sub_field() アドオン Repeater Field 用の関数

<?php\
the_sub_field($sub_field_name);
?>
update_field()
// Field Name で更新
$field_name = "text_field";
$value = "some new string";
update_field( $field_name, $value );
// Field Key で更新
$field_key = "field_5039a99716d1d";
$value = "some new string";
update_field( $field_key, $value );
// 配列で更新
$field_key = "field_5039a9973jsd1d";
$value = array("red", "blue", "yellow");
$post_id = 123;
update_field( $field_key, $value, $post_id );
get_field_object() フィールドのオブジェクトを取得します。

■ 参照可能なオブジェクトのメンバー変数
Array
(
    [key] => field_4fea85f5320da
        [label] => Text Field
    [name] => text_field
        [type] => text
            [instructions] =>
                [required] => 0
                    [default_value] =>
                        [formatting] => html
                            [order_no] => 0
    [value] => Use the option parameter to toggle loading the value
)
<?php
$field_name = "text_field";
$field = get_field_object($field_name);
echo $field['label'] . ': ' . $field['value'];
?>
Hooks & Filters
Shortcode ショートコードが利用できます。the_field() と同じ結果になります。

■ 記事欄