Skip to content

Instantly share code, notes, and snippets.

@trey8611
Last active November 2, 2022 09:18
Show Gist options
  • Star 3 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save trey8611/617bbfa93b0298db281341a3ea58a664 to your computer and use it in GitHub Desktop.
Save trey8611/617bbfa93b0298db281341a3ea58a664 to your computer and use it in GitHub Desktop.
WP All Import & ACF Add-On - How to append data to repeaters | pmxi_saved_post

Append ACF Repeater Data

It's not possible to append a row to an ACF repeater field without a custom code workaround that utilizes our API: http://www.wpallimport.com/documentation/developers/action-reference/.

The following is an example to show you how this can be done. You will almost certainly need to adjust the code snippet to make it work with your data/site.

  1. Create a new "Manual Record Matching" import that updates the post(s): http://www.wpallimport.com/documentation/recurring/manual-record-matching/

  2. Store the ACF data in your own dummy custom field: http://d.pr/i/3Si4ad.

  3. Add some code in the Function Editor that grabs that data and appends it to the ACF field.

Example code:

add_action( 'pmxi_saved_post', 'soflyy_add_data', 10, 3 );

function soflyy_add_data( $id, $xml, $update ) {
	$selector = 'basic_repeater'; // The Parent field name
	$subfield1 = 'repeater_text'; // The repeating field you want to add data to
	
	if ( $value = get_post_meta( $id, 'my_repeater_data', true ) ) {
		$row = array( $subfield1 => $value );
		add_row( $selector, $row, $id );
	}
	delete_post_meta( $id, 'my_repeater_data' );
}
  1. On step 4 of the import, choose to only update the custom field that you're importing: http://d.pr/i/WfZKAT.

Check for duplicates

Here's a different example snippet that shows how you could check for duplicates when appending repeater data:

add_action( 'pmxi_saved_post', 'my_update_results', 10, 3 );

function my_update_results( $id, $xml, $is_update ) {
	$year    = get_post_meta( $id, '_year', true );
	$results = get_post_meta( $id, '_results', true );
	
	$repeater_selector = 'yearly_results';
	$year_selector     = 'year';
	$results_selector  = 'results';
	
	$row = array( 
		$year_selector    => $year, 
		$results_selector => $results 
	);
	
	if ( ! my_is_duplicate_acf_row( $row, $repeater_selector, $id ) ) {	
		add_row( $repeater_selector, $row, $id );
	}
	
	delete_post_meta( $id, '_year' );
	delete_post_meta( $id, '_results' );
}

function my_is_duplicate_acf_row( $row, $selector, $id ) {
	$rows = array();
	if ( have_rows( $selector, $id ) ) {
		$i = 0;
		while ( have_rows( $selector, $id ) ) {
			$existing_row = the_row( TRUE );
			$existing_row = maybe_unserialize( $existing_row );
			$row          = maybe_unserialize( $row );
			if ( $row === $existing_row ) {
				return TRUE;
			}
		}
	}
	return FALSE;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment