Skip to content

Instantly share code, notes, and snippets.

@aaronranard
Last active October 23, 2015 22:23
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save aaronranard/53ff4a44362927711d37 to your computer and use it in GitHub Desktop.
Save aaronranard/53ff4a44362927711d37 to your computer and use it in GitHub Desktop.
acf's delete_sub_field call http://support.advancedcustomfields.com/forums/topic/remove-sub_field/ only makes the value null it doesn't actually delete the row. This does.
<?php
/*
* deleteSubField
*
* This function will delete a value of a sub field entirely and replace the rows correctly.
* ACF's built in delete_sub_field only sets the value to null
*
* @param $field_key (string) the field key of the top level custom field
* @param $repeater_key (string) the field key of the repeater element
* @param $post_id (int) the post_id of which the repeater is stored in
* @param $repeater_obj (mixed) the value of the row to be deleted from the repeater
* @param $field_name (string) the name of the field in the repeater to be searched on
* @return (boolean)
*/
function deleteSubField( $post_id, $field_key, $repeater_key, $field_name, $repeater_obj ) {
$value = get_field( $field_key, $post_id );
$pos = 1;
$repeater_position = null;
// Loop through the repeater to find the position of the correct row
foreach($value as $key=>$field)
{
if($field[$field_name] === $repeater_obj)
{
unset($value[$key]);
$repeater_position = $pos;
}
$pos++;
}
if ($repeater_position == null)
{
// Value not found
return false;
}
for( $i = $repeater_position; $i < count($value); $i++)
{
// Move each item in the array back one, starting at the position of the repeater
update_sub_field( array($field_key, $i, $repeater_key), $value[$i + 1], $post_id);
}
// Now that each element has been moved back one, delete the last repeater item
delete_sub_field( array($field_key, count($value) + 1, $repeater_key), $post_id);
// Update repeater value with new length which will remove the last row
update_field( $field_key, $value, $post_id);
return true;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment