update_sub_field()

Overview

This function can be used to update an existing sub field value. If used within a have_rows() loop, the current row will be used to update the sub field value. If used outside of a have_rows() loop, the rows and parents can be specified to target the correct value place.

Change Log

  • Added in version 5.0.0

Parameters

update_sub_field( $selector, $value, $post_id );
  • $selector: (required) The sub field name or key, or an array of ancestors and row numbers
  • $value: (required) The new value to save in the database
  • $post_id: (optional) The post ID of which the value is saved to

Return

This function will return true upon success or false upon failure.

Notes

  • Row numbers start from 1 (not 0). For example, the first row of values is considered $i = 1
  • It is possible to change the row index starting point so that row numbers start from 0 using the row_index_offset setting.

Examples

Inside have_rows() loop

This example will loop through a repeater field and update a sub field using the current row number in the value. This shows how to use the update_sub_field() function withing a have_rows() loop.

<?php 

if( have_rows('repeater') ) {

	$i = 0;

	while( have_rows('repeater') ) {

		the_row();

		$i++;

		update_sub_field('caption', "This caption is in row {$i}");

	}

}

?>

Outside have_rows() loop

This example will update a sub field value outside of a have_rows() loop. Please note that the $selector parameter is given an array containing a mixture of field names and row numbers. This array should read from left to right, the parents to children relationship padded by the row number.

This example will update a sub field on the first row of a repeater field.

<?php 

update_sub_field( array('repeater', 1, 'caption'), 'This caption is for the first row of the repeater!' );

?>

Nested repeater fields

The update_sub_field() function will work correctly with nested repeater fields both inside and outside of the have_rows() loop. This example will demonstrate how this is possible in both formats.

<?php 

// parent repeater
if( have_rows('repeater') ) {

	$parent_i = 0;

	while( have_rows('repeater') ) {

		the_row();

		$parent_i++;

		// child repeater
		if( have_rows('sub_repeater') ) {

			$child_i = 0;

			while( have_rows('sub_repeater') ) {

				the_row();

				$child_i++;

				update_sub_field('sub_sub_field', "This value is for repeater row {$parent_i}, and sub_repeater row {$child_i}");

			}
			// while

		}
		// if

	}
	// while

}
// if

?>
<?php 

update_sub_field( array('repeater', 1, 'sub_repeater', 2, 'sub_sub_field'), 'This value is for repeater row 1, and sub_repeater row 2!' );

 ?>

Related