0
2

More than 3 years have passed since last update.

Advance Custom fields(ACF)の出力方法まとめ

Last updated at Posted at 2020-12-25

Advance Custom fields(ACF)とは

wordpressでカスタム投稿が出来るプラグインで一番有名だと思います。
Advance Custom fields
image.png

管理画面での設定方法は簡単なのですが、出力が少し難しいので覚書しておきます。

テキスト出力例

image.png


<?php
$field_name = get_field('name');
$field_kana = get_field('kana');

//nameの値が空でなければ
if($field_name){echo '<p>'.$field_name.'</p>';}
//kanaの値が空でなければ
if($field_kana){echo '<p>'.$field_kana.'</p>';}
?>

ラジオボタン・選択肢出力例

image.png

<?php
$select_sex = get_field('sex');
$select_birthplace = get_field('birthplace');

//sexが空でなければ
if($select_sex){
    {echo '<p>'.$select_sex.'</p>';}
}
//birthplaceが空でなければ
if($select_birthplace){
    {echo '<p>'.$select_birthplace.'</p>';}
}
?>

選択肢が複数回答可の場合

image.png

1.foreachを利用して、select_scaleの値をchildに代入
2.childが配列(=2個以上の値が選択)だったら、child['label']で値を1つずつ出力
3.それ以外(=選択肢1個)の場合、childをそのまま出力
しています。

<?php
$select_scale = get_field('scale');

if($select_scale){
    echo '<ul>';
    foreach($select_scale as $child){
        echo '<li>';
        if(is_array($child)){
            //bothの場合、ラベルを出力
            echo $child['label'];
        }else{
            //単独の返り値の場合の出力
            echo $child;
        }
        echo '</li>';
    }
    echo '</ul>';
}
?>

画像

<?php the_field('img'); ?>

まとめ

値を取得する時はget_filedで変数に代入

$field_ラベル名 = get_field('ラベル名');

出力する時は、値が空かどうか判断してから出力すると良い

if($field_ラベル名){echo '<p>'.$field_ラベル名.'</p>';} 
0
2
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
2