WordPressのプラグイン「Advanced Custom Fields」で画像を出力させるときのメモ
Advanced Custom Fieldsの設定側で、画像の「返り値」を何にしたかで、出力方法が異なる
返り値の種類は、画像オブジェクト、画像URL、画像IDの3つ。
画像オブジェクト
画像に関する情報を色々取得できます。
公式サイトの詳細ページ
https://www.advancedcustomfields.com/resources/image/
画像オブジェクトで出力するサンプル
<?php
$image = get_field('image');
if( !empty($image) ):
// vars
$url = $image['url'];
$title = $image['title'];
$alt = $image['alt'];
$caption = $image['caption'];
// thumbnail
$size = 'thumbnail';
$thumb = $image['sizes'][ $size ];
$width = $image['sizes'][ $size . '-width' ];
$height = $image['sizes'][ $size . '-height' ];
if( $caption ): ?>
<div class="wp-caption">
<?php endif; ?>
<a href="<?php echo $url; ?>" title="<?php echo $title; ?>">
<img src="<?php echo $thumb; ?>" alt="<?php echo $alt; ?>" width="<?php echo $width; ?>" height="<?php echo $height; ?>" />
</a>
<?php if( $caption ): ?>
<p class="wp-caption-text"><?php echo $caption; ?></p>
</div>
<?php endif; ?>
<?php endif; ?>画像URL
画像のURLをそのまま返します。
画像をそのまま出力したいときには一番簡単ですね。
<?php if( get_field('image') ): ?>
<img src="<?php the_field('image'); ?>" />
<?php endif; ?>画像ID
文字通り画像のIDを出力します。
IDを使ってサイズなどを指定することもできます。
公式サイトから
<?php
$image = get_field('image');
$size = 'full'; // (thumbnail, medium, large, full or custom size)
if( $image ) {
echo wp_get_attachment_image( $image, $size );
}
?>ワイド、ハイトを指定する
<?php
$attachment_id = get_field('image');
$size = "full"; // (thumbnail, medium, large, full or custom size)
$image = wp_get_attachment_image_src( $attachment_id, $size );
$attachment = get_post( get_field('image') );
$alt = get_post_meta($attachment->ID, '_wp_attachment_image_alt', true);
$image_title = $attachment->post_title;
?>
<p><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; ?>" /></p>カテゴリーの画像を設定して出力する
Advanced Custom Fieldsでカテゴリ用のフィールドをしてする場合は、位置のルールを「Taxsonomy Term」に設定しカテゴリを選ぶ。
<?php
$args = array(
'parent' => 5, //親カテゴリを指定
'exclude' => 20 //除外カテゴリを指定
);
$categories = get_categories($args);
foreach ( $categories as $category ) {
$attachment_id = get_field('categ_img',$post_id);
$size = "full"; // (thumbnail, medium, large, full or custom size)
$attachment = get_post( get_field('categ_img') );
$alt = get_post_meta($attachment->ID, '_wp_attachment_image_alt', true);
$image_title = $attachment->post_title;
$cat_id = $category->cat_ID;
$post_id = 'category_'.$cat_id;
$cat_name = $category->name;
$catimg = get_field('categ_img',$post_id);
$catimages = wp_get_attachment_image_src( $catimg, $size );
?>
<div class="column catlist cat_<?php echo $cat_id; ?>">
<a href="<?php echo get_category_link( $category->term_id ); ?>" class="cat_<?php echo $cat_id; ?>">
<?php
echo '<img src="'.$catimages[0].'" alt="'.$cat_name.'" width="'.$image[1].'" height="'.$image[2].'">';
echo $category->name; ?>
</a>
</div>
<?php }?>