概要
get_row_layout
関数は、Advanced Custom Fields (ACF) プラグインで特にFlexible Contentフィールドを使用する際に、have_rows
ループ内の現在の行レイアウト名を返します。この機能は、複雑なレイアウトを持つコンテンツの表示をカスタマイズする際に非常に便利です。主に以下のようなシナリオでよく使われます:
- 動的なページナビゲーションの作成
- 異なるテンプレートに基づく異なるコンテンツの表示
- 条件に基づいたCSSクラスの追加
- カスタム投稿タイプのレイアウトの管理
- 各行に対する特定のフィールドの取得
- テンプレートファイルでのパーツ分けによるコードの整理
構文
get_row_layout();
パラメータ
この関数はパラメータを持ちません。
戻り値
現在の行のレイアウト名を文字列として返します。
使用可能なバージョン
- 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('flexible_content_field') ):
while( have_rows('flexible_content_field') ) : the_row();
if( get_row_layout() == 'text_block' ):
get_template_part('template-parts/text-block');
elseif( get_row_layout() == 'image_block' ):
get_template_part('template-parts/image-block');
endif;
endwhile;
endif;
このコードは、Flexible Contentフィールド内の各行のレイアウトタイプに基づいて異なるテンプレートパーツを読み込むサンプルです。
サンプルコード2: CSSクラスを動的に変更する
if( have_rows('flexible_content') ):
while( have_rows('flexible_content') ) : the_row();
$layout = get_row_layout();
echo '<div class="' . esc_attr($layout) . '">';
the_sub_field('content');
echo '</div>';
endwhile;
endif;
このコードは、現在の行レイアウト名をCSSクラスとして適用し、各行の内容を囲っています。
サンプルコード3: レイアウト毎に異なる設定を取得
if( have_rows('custom_layouts') ):
while( have_rows('custom_layouts') ) : the_row();
$layout_type = get_row_layout();
if($layout_type == 'image_gallery'){
$images = get_sub_field('images');
// ギャラリー画像を表示するコード
}
endwhile;
endif;
このコードは、特定のレイアウトタイプに基づいてサブフィールドからデータを取得し、条件に応じた処理を行っています。
サンプルコード4: ACFのFlexible Contentの構成に基づくループ
if( have_rows('content_blocks') ):
while( have_rows('content_blocks') ) : the_row();
switch( get_row_layout() ) {
case 'hero':
// ヒーローセクションの処理
break;
case 'features':
// 特徴セクションの処理
break;
}
endwhile;
endif;
このコードは、スイッチ文を使用して異なるレイアウトに基づいて内容を振り分けます。
サンプルコード5: レイアウト名を利用してフィールドの取得
if( have_rows('page_sections') ):
while( have_rows('page_sections') ) : the_row();
$layout = get_row_layout();
if($layout == 'contact_form'):
get_template_part('form', 'contact');
elseif($layout == 'quote'):
echo '<blockquote>' . get_sub_field('quote_text') . '</blockquote>';
endif;
endwhile;
endif;
このコードは、現在のレイアウトが「contact_form」の場合に特定のフォームテンプレートを読み込み、別のレイアウトが「quote」の場合には引用文を表示する例です。