delete_sub_field()

Overview

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

Change Log

  • Added in version 5.0.0

Parameters

delete_sub_field( $selector, [$post_id] );
  • $selector (string|array) (required) The sub field name or key, or an array of ancestors and row numbers
  • $post_id (mixed) (Optional) The post ID where the value is saved. Defaults to the current post

Return

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

Examples

Inside have_rows() loop

This example will loop through a repeater field and delete a sub field value. This shows how to use the delete_sub_field() function withing a have_rows() loop.

<?php 

if( have_rows('repeater') ) {

	while( have_rows('repeater') ) {

		the_row();
		
		if( get_sub_field('color') == 'red' ) {
			
			delete_sub_field('color');
			
		}
		
	}

}

?>

Outside have_rows() loop

This example will delete 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.

  • 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.

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

<?php 

delete_sub_field( array('repeater', 1, 'color') );

?>

Nested repeater fields

The delete_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') ) {

	while( have_rows('repeater') ) {

		the_row();

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

			while( have_rows('sub_repeater') ) {

				the_row();

				delete_sub_field('sub_sub_field');

			}
			// while

		}
		// if

	}
	// while

}
// if

?>
<?php 

delete_sub_field( array('repeater', 1, 'sub_repeater', 1, 'sub_sub_field') );

?>

Related