add_sub_row()

Overview

This function will add (append) a row of values to an existing repeater field or flexible content sub field value. This function is different to add_row() which will add a row to 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

add_sub_row( $selector, $row, $post_id );
  • $selector: (mixed) The sub field name or key, or an array of ancestors and row numbers (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 the new count of rows 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 add an extra row of data to each sub repeater field (r2).

<?php 

if( have_rows('r1') ) {

	while( have_rows('r1') ) {

		the_row();
		
		$row = array(
			't1' => 'New t1 value',
			't2' => 'New t2 value'
		);

		add_sub_row('r2', $row);

	}

}

?>

Outside have_rows() loop

This example will add a row of values to a sub field 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 

// add to r1 (row 1) => r2
$row1 = array(
	't1' => 'r1 (row 1) => r2 (new row) => t1',
	't2' => 'r1 (row 1) => r2 (new row) => t2'
);

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


// add to r1 (row 2) => r2
$row2 = array(
	't1' => 'r1 (row 2) => r2 (new row) => t1',
	't2' => 'r1 (row 2) => r2 (new row) => t2'
);

add_sub_row( array('r1', 2, 'r2'), $row2 );

?>

Related