wordpressのAdvanced Custom Fieldsでフィールドの値を取得して出力するテンプレート。

【基本的な方法】

Advanced Custom Fields

フィールドの値を取得して表示するには、「the_field()」を使います。

post_customなどのタグを使うと、プレビューなどが反映されないため、
Advanced Custom Fields特有のタグを使う必要がある。

the_field('field_name_01');

フィールドの値を取得して変数に代入して使う場合などは、「get_field()」を使います。

$hoge = get_field('field_name_01');

【フィールドタイプ:テキスト】

取得したフィールド(フィールド名:field_name_01)に何か入力されていたら、値を表示する場合の例。

$text = get_field('field_name_01');
if ( $text )  {
    echo $text;
}

【フィールドタイプ:テキストエリア】

改行で区切られたデータが入っているフィールド(フィールド名:field_name_01)の値を取得し、リスト形式に成形して表示する場合の例。

$fieldData = explode("\n",get_post_meta($post->ID,'field_name_01',true) );
$i = 0;
echo "<ul>";
foreach ($fieldData as $value){
    if ( $value ){
        echo '<li>' . $value . '</li>';
    }
    $i++;
echo "</ul>";
}

【フィールドタイプ:数値】
取得したフィールド(フィールド名:field_name_01)の値を、千位毎の区切り及び小数点以下第一位まで表示させる場合の例。

echo number_format( get_post_meta($post->ID,'field_name_01',true) , 1 );

【フィールドタイプ:Wysiwyg エディタ】

取得したフィールド(フィールド名:field_name_01)の値に画像にリンクを貼っている箇所が存在したら、aタグに「rel=”lightbox”」を付加する場合の例。

$pattern = "/<a(.*?)href=('|\")(.*?).(bmp|gif|jpeg|jpg|png)('|\")(.*?)>/i";
$replacement = '<a$1href=$2$3.$4$5 rel="lightbox"$6>';

$dataText = get_field("field_name_01", $post->ID);
$dataText = preg_replace ( $pattern , $replacement , $dataText);

echo $dataText;

【フィールドタイプ:画像】

取得したフィールド(フィールド名:field_name_01)の画像をlargeサイズで表示する場合の例。(lightboxを使う前提で、aタグには「rel=”lightbox”」をつけています。)

※ フィールド名「field_name_01」を定義する時に、「返り値」は「画像 ID」を指定しておいてください。

<?php
    $attachment_id = get_field('field_name_01');
    $size = "large"; // (thumbnail, medium, large, full or custom size)
    $image = wp_get_attachment_image_src( $attachment_id, $size );
    $attachment = get_post( get_field('field_name_01') );
    $alt = get_post_meta($attachment->ID, '_wp_attachment_image_alt', true);
    $image_title = $attachment->post_title;
?>

<a href="<?php echo wp_get_attachment_url( get_field( 'field_name_01',$post->ID) ); ?>" rel="lightbox"><img src="<?php echo $image[0]; ?>" width="<?php echo $image[1]; ?>" height="<?php echo $image[2]; ?>" alt="<?php echo $alt; ?>" title="<?php echo $image_title; ?>" /></a>

【フィールドタイプ:画像IDを取得して表示】

//画像IDの取得
$image_id = post_custom('[画像アップロードのカスタムフィールド名]');
//画像IDから画像を表示 $sizeに表示サイズを設定(デフォルトは'thumbnail')
echo wp_get_attachment_image($image_id, $size); 

【フィールドの値をチェックして表示】

$text = get_field('my_custom_01');
if($text) :
echo $text;
endif;

Copyright © All Rights Reserved · Green Hope Theme by Sivan & schiy · Proudly powered by WordPress