has_sub_field()


WordPressのhas_sub_field()関数は、Advanced Custom Fields(ACF)プラグインで使用される関数で、現在のループ内にサブフィールドが存在するかどうかをチェックします。この関数は、主にリピーターフィールドやフレキシブルコンテンツフィールド内で使用されます。

構文

has_sub_field( $field_name, $post_id );

引数の説明:

  • $field_name(string) — チェックするサブフィールドの名前を指定します。
  • $post_id(mixed) — オプション。投稿IDを指定します。指定しない場合、現在の投稿が使用されます。

例1: リピーターフィールド内のサブフィールドをチェック

リピーターフィールド内にサブフィールドが存在するかどうかをチェックし、存在する場合はその値を表示します。

<?php if( have_rows('repeater_field') ): while( have_rows('repeater_field') ): the_row(); if( has_sub_field('sub_field') ): echo get_sub_field('sub_field'); endif; endwhile; endif; ?>

例2: フレキシブルコンテンツフィールド内のサブフィールドをチェック

フレキシブルコンテンツフィールド内にサブフィールドが存在するかどうかをチェックし、存在する場合はその値を表示します。

<?php if( have_rows('flexible_content_field') ): while( have_rows('flexible_content_field') ): the_row(); if( has_sub_field('sub_field') ): echo get_sub_field('sub_field'); endif; endwhile; endif; ?>

例3: 特定の投稿IDでサブフィールドをチェック

特定の投稿IDに対してサブフィールドが存在するかどうかをチェックします。

<?php if( has_sub_field('sub_field', 123) ): echo get_sub_field('sub_field', 123); endif; ?>

例4: リピーターフィールド内のサブフィールドをループ処理

リピーターフィールド内のサブフィールドをループ処理し、すべての値を表示します。

<?php if( have_rows('repeater_field') ): while( have_rows('repeater_field') ): the_row(); if( has_sub_field('sub_field') ): while( has_sub_field('sub_field') ): echo get_sub_field('sub_field'); endwhile; endif; endwhile; endif; ?>

例5: サブフィールドが存在しない場合の処理

サブフィールドが存在しない場合に代替テキストを表示します。

<?php if( has_sub_field('sub_field') ): echo get_sub_field('sub_field'); else: echo 'サブフィールドが存在しません。'; endif; ?>

例6: サブフィールドの値を配列として取得

サブフィールドの値を配列として取得し、それをループ処理して表示します。

<?php if( has_sub_field('sub_field') ): $values = get_sub_field('sub_field'); foreach( $values as $value ): echo $value; endforeach; endif; ?>

例7: サブフィールドの値を条件付きで表示

サブフィールドの値が特定の条件を満たす場合にのみ表示します。

<?php if( has_sub_field('sub_field') ): $value = get_sub_field('sub_field'); if( $value == '特定の値' ): echo $value; endif; endif; ?>

例8: サブフィールドの値をJSON形式で出力

サブフィールドの値をJSON形式で出力します。

<?php if( has_sub_field('sub_field') ): $value = get_sub_field('sub_field'); echo json_encode($value); endif; ?>

注意点

  • has_sub_field()は、リピーターフィールドやフレキシブルコンテンツフィールド内でのみ使用できます。
  • サブフィールドが存在しない場合、has_sub_field()falseを返します。
  • サブフィールドの値を取得するには、get_sub_field()を使用します。