7月
22
2013

Advanced Custom Fieldsでフィールドの値を取得して出力する5つのパターン。

WordPress
Advanced Custom Fieldsプラグインを使ったカスタムフィールド操作の練習メモ。フィールドの値を取得して表示させる方法を纏めてみました。



 
 
0.基本的な方法

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

the_field('field_name_01');

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

$hoge = get_field('field_name_01');

 
 
1.フィールドタイプ:テキスト

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

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

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

改行で区切られたデータが入っているフィールド(フィールド名: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>";
}

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

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

 
 
4.フィールドタイプ: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;

【参考サイト】
》AfroNamiHeiの箱 – WordPressでlightbox 2.0を使う

サイトでlightboxを使っていて、Wysiwyg エディタを指定した項目で「メディアを追加」で画像を貼り付けた場合、「rel=”lightbox”」が付かずにlightboxが動作しないので値を取得して表示する際に付加してあげる必要があるようです。
 
 
5.フィールドタイプ:画像

取得したフィールド(フィールド名: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>

【参考サイト】
》Webcre Archive – Advanced Custom Fields で画像を挿入してみる

最後の画像を挿入する部分が一番悩みましたが、そこはWordPress。ググったらドンぴしゃな記事があり、無事解決できました。あ、やまりゅうさん、ご無沙汰してます&ありがとうございます。
 
 

 


2024年4月
1234567
891011121314
15161718192021
22232425262728
2930  

Archives

Recommended