update_sub_row()

Overview

This function will update a row of values of an existing repeater field or flexible content sub field value. This function is different to update_row() which will update a row of a parent field. You may use this function inside or outside of a have_rows() loop to target which sub field’s value you intend to modify.

Changelog

  • Added in version 5.4.7

Parameters

update_sub_row( $selector, $i, $row, $post_id );
  • $selector: (mixed) The sub field name or key, or an array of ancestors and row numbers (required)
  • $i: (int) The row number you wish to update (required)
  • $row: (array) The new row value to save in the database (required)
  • $post_id: (mixed) 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

The following examples use a repeater field called ‘Parent’ that contains a child repeater. Here is an illustration of the sub fields:

r1 (repeater)
– r2 (repeater)
— t1 (text)
— t2 (text)

Inside have_rows() loop

This example will loop through a repeater field (r1) and update the first row of the sub repeater field (r2).

<?php 

if( have_rows('r1') ) {

	$i = 0;
	
	while( have_rows('r1') ) {

		the_row();
		
		$i++;
		
		$row = array(
			't1' => 'r1 (row ' . $i . ') => r2 (row 1) => t1',
			't2' => 'r1 (row ' . $i . ') => r2 (row 1) => t2'
		);

		update_sub_row('r2', 1, $row);

	}

}

?>

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.

<?php 

// update parent row 1 => sub row 1
$row1 = array(
	't1' => 'r1 (row 1) => r2 (row 1) => t1',
	't2' => 'r1 (row 1) => r2 (row 1) => t2'
);

update_sub_row( array('r1', 1, 'r2'), 1, $row1 );


// update parent row 2 => sub row 1
$row2 = array(
	't1' => 'r1 (row 2) => r2 (row 1) => t1',
	't2' => 'r1 (row 2) => r2 (row 1) => t2'
);

update_sub_row( array('r1', 2, 'r2'), 1, $row2 );


// update parent row 2 => sub row 2
$row3 = array(
	't1' => 'r1 (row 2) => r2 (row 2) => t1',
	't2' => 'r1 (row 2) => r2 (row 2) => t2'
);

update_sub_row( array('r1', 2, 'r2'), 2, $row3 );

?>

Related