the_sub_field()

Overview

This function will display a sub field value from a repeater field or flexible content field loop. This function is used within a have_rows() loop.

This function is the same as echo get_sub_field('name');.

Parameters

<?php the_sub_field($sub_field_name, $format_value); ?>
  • $sub_field_name (string) the name of the field to be retrieved. eg “page_content” (required)
  • $format_value (boolean) whether or not to format the value loaded from the db. Defaults to true (optional).

Usage

Basic (Repeater)

This example shows how to loop through a Repeater field and display a sub field value.

<?php 
    
if( have_rows('parent_field') ):

    while( have_rows('parent_field') ) : the_row(); 
        
        ?>
        <p><?php the_sub_field('sub_field'); ?></p>
		<?php
			
    endwhile;

endif;

?>

Basic (Flexible Content)

This example shows how to loop through a Flexible Content field and display a sub field value.

<?php 
    
if( have_rows('parent_field') ):

    while( have_rows('parent_field') ) : the_row();
		
		// get layout
		$layout = get_row_layout();
		
		
		// layout_1
		if( $layout === 'layout_1' ): ?>
			
			<div class="layout-1">
				<p><?php the_sub_field('sub_field_1'); ?></p>
			</div>

		<?php // layout_2	
		elseif( $layout === 'layout_2' ): ?>
			
			<div class="layout-2">
				<p><?php the_sub_field('sub_field_2'); ?></p>
			</div>
			
		<?php endif;

    endwhile;

endif;

?>

Nested

This example shows how to loop through a nested Repeater field and display a sub field value.

<?php 

// parent loop
if( have_rows('parent_repeater') ):

    while( have_rows('parent_repeater') ) : the_row();
    
    	?>
		
		<div class="row">
			
			<h3><?php the_sub_field('parent_title'); ?></h3>
			
			<?php 
				
			// child loop
			if( have_rows('child_repeater') ): ?>
				
				<ul>
			
			    <?php while( have_rows('child_repeater') ) : the_row(); ?>
				
					<li><b><?php the_sub_field('child_title'); ?></b> <?php the_sub_field('child_value'); ?></li>
			
				<?php endwhile; ?>
				
				</ul>
			
			<?php endif;
			// end child loop
			
			?>
			
		</div>
		
		<?php		
		
    endwhile;

endif;
// end parent loop

?>

Related