Advanced Custom Fieldsのいろいろ

yasuko
ROCK IN JAPAN FESTIVAL 2022残念

いつもACFを使うたびにどうだったっけなーと検索しながら手探りで前進するタイプ。

もっとスマートにワードプレス使いこなしたいわ。

出力タグいろいろ

基本の出力

<?php the_field('フィールド名'); ?>

画像の出力

返り値のフォーマットを画像 URLにして

<img src="<?php the_field('フィールド名'); ?>" alt=""/>

チェックボックスの出力

項目を<ul><li></li></ul>形式で出力するパターン

<?php
$cfcb = get_field_object( 'フィールド名' );
$cfcbId = get_post_meta( $post->ID, 'フィールド名' );
$cfcbId = $cfcbId[ 0 ];
if ( $cfcb ) {
  echo '
<ul class="">';
  foreach ( $cfcbId as $v ) {
    echo '<li class="">' . $cfcb[ 'choices' ][ $v ] . '</li>';
  }
  echo '</ul>';
}
?>

タクソノミーの出力(リンクなし) チェックボックス

項目を<ul><li></li></ul>形式で出力するパターン

<?php
$terms = get_the_terms( $post->ID, 'フィールド名' );
echo '<ul class="">';
    foreach ( $terms as $term ) {
      echo'<li class="">' . $term->name . '</li>';
}
echo "</ul>";
?>

タクソノミーの出力(リンクなし)  ラジオボタン

<?php
$term = get_field( 'フィールド名' );
if ( $term )
  echo esc_html( $term->name );
?>

文字数を制限して出力

50文字以内なら、そのまま出力。

50文字を越えていたら49文字の後ろに  をつけて出力。

<?php
if ( mb_strlen( get_field( 'フィールド名' ) ) > 50 ) {
  $text = mb_substr( get_field( 'フィールド名' ), 0, 49 );
  echo $text . '…';
} else {
echo get_field( 'フィールド名' );
}
?>

文字数を制限して改行を取り除いて出力

<?php
$text = get_field('フィールド名');
$str = str_replace(array('<br>', '
<br />', "\r\n", "\n", "\r", ' '), ", $text);
echo mb_substr(($str), 0, 50);
?>

テキストエリアを改行させる

<?php
$post_id = get_the_ID();
$text = nl2br( get_post_meta( $post_id, 'textarea', true ) );
?>
<?php if ($text) : ?>
<p><?php echo $text; ?></p>
<?php endif; ?>

公式サイト

Advanced Custom Fields