概要
have_rows
関数は、Advanced custom fields (ACF) プラグインで、親フィールドの値をループするために使用されます。この関数は、特にリピートフィールドや柔軟なコンテンツフィールドを扱う際に非常に便利です。以下のようなシナリオでよく使われます:
- リピートフィールドのエントリを表示する
- 柔軟なコンテンツフィールドの各コンポーネントをループする
- カスタム投稿タイプの特定のメタデータを取得する
- お問い合わせフォームやレビューセクションの動的コンテンツを表示する
- 特定の条件に基づいてカスタムフィールドをフィルタリングする
- 自動化されたレイアウトシステムを構築する
構文
have_rows( $field_name, $post_id );
$field_name
(string):リピートまたは柔軟なコンテンツのフィールド名。$post_id
(int|string、オプション):データを取得したい投稿の ID。指定しなければ、現在の投稿が使用されます。
パラメータ
field_name
: ループするカスタムフィールドの名称(必須)。post_id
: 指定オプションの投稿ID。
戻り値
bool
: 行が存在する場合はtrue
、そうでない場合はfalse
を返します。
対応バージョン
- Advanced custom fields (ACF) バージョン: 5.0以降
- WordPress バージョン: 4.0以降
この関数のアクションでの使用可能性
アクション名 | 使用例 |
---|---|
mu_plugin_loaded | |
registered_post_type | |
plugins_loaded | |
wp_roles_init | |
setup_theme | |
after_setup_theme | |
set_current_user | |
init | |
register_sidebar | |
wp_loaded | |
send_headers | |
parse_query | |
pre_get_posts | |
wp | |
template_redirect | |
get_header | |
wp_head |
サンプルコード
サンプルコード 1
if ( have_rows( 'team_members' ) ) {
while ( have_rows( 'team_members' ) ) {
the_row();
$name = get_sub_field( 'name' );
echo '<div>' . esc_html( $name ) . '</div>';
}
}
このコードは、「team_members」というリピートフィールドを取得し、各メンバーの名前を表示します。
サンプルコード 2
if ( have_rows( 'services' ) ) {
echo '<ul>';
while ( have_rows( 'services' ) ) {
the_row();
$service = get_sub_field( 'service_name' );
echo '<li>' . esc_html( $service ) . '</li>';
}
echo '</ul>';
}
このコードは、リピートフィールド「services」の各サービス名をリスト形式で表示します。
サンプルコード 3
if ( have_rows( 'portfolio_items' ) ) {
while ( have_rows( 'portfolio_items' ) ) {
the_row();
$image = get_sub_field( 'portfolio_image' );
echo '<img src="' . esc_url( $image ) . '" alt="">';
}
}
このコードは、「portfolio_items」というリピートフィールドからポートフォリオ画像を取得し、表示します。
サンプルコード 4
if ( have_rows( 'testimonials' ) ) {
while ( have_rows( 'testimonials' ) ) {
the_row();
$quote = get_sub_field( 'quote' );
$author = get_sub_field( 'author' );
echo '<blockquote>' . esc_html( $quote ) . '<cite>' . esc_html( $author ) . '</cite></blockquote>';
}
}
このコードは、テストモニアル(推薦文)フィールドから引用を取得し、著者名と共に表示します。
サンプルコード 5
if ( have_rows( 'product_features' ) ) {
echo '<div class="features">';
while ( have_rows( 'product_features' ) ) {
the_row();
$feature = get_sub_field( 'feature_description' );
echo '<p>' . esc_html( $feature ) . '</p>';
}
echo '</div>';
}
このコードは、製品の特徴をリピートフィールド「product_features」から取得し、段落形式で表示します。