phpwordpressadvanced-custom-fieldswpallimport

Add ACF Repeater Row Without Overwriting Existing Data


I’m working with WP All Import and Advanced Custom Fields (ACF). I need help ensuring that when importing data, a new row is added to a repeater field without overwriting existing rows.

Here's the specific scenario: I have a parent repeater field called sellers with the following subfields:

company (Merchant name) price (Price) link (Link) During the import, I need to:

Check if the value of company matches the incoming {company_name[1]} from the record. If it already exists, do nothing. If it doesn’t exist, add a new row to the repeater field with the following values

bedrijf = {company_name[1]}
prijs = {search_price[1]}
link = {y_link[1]}

Currently, the import overwrites the entire repeater field, removing existing rows, which I need to avoid.

I tried:


add_action('pmxi_saved_post', function($post_id, $xml_data, $import_id) {
    if (get_post_type($post_id) !== 'product') return;

    $selector = 'sellers';
    $subfield1 = 'company';
    $subfield2 = 'prijs';
    $subfield3 = 'link';

    $merchant_name = $xml_data['company_name'][1] ?? '';
    $search_price = $xml_data['search_price'][1] ?? '';
    $aw_deep_link = $xml_data['company_name'][1] ?? '';

    if (empty($merchant_name)) return;

    $existing_rows = get_field($selector, $post_id) ?: [];
    foreach ($existing_rows as $row) {
        if ($row[$subfield1] === $merchant_name) return;
    }

    $existing_rows[] = [
        $subfield1 => $company_name,
        $subfield2 => $search_price,
        $subfield3 => $y_link,
    ];
    update_field($selector, $existing_rows, $post_id);
}, 10, 3);

But I am not able to get it to work.


Solution

  • Found the solution for me!

    The data needs to be stored somewhere in order for WpAllImport to get it.

    Therefor I made dummy fields. and delete the data in the dummy fields after the import.

    add_action( 'pmxi_saved_post', 'acf_add_row', 10, 3 );
    function acf_add_row( $id, $xml, $update ) {
        $repeater = 'sellers';
        $subfield = 'company';
        if ( $value = get_post_meta( $id, 'dummy_company', true ) ) {
            $row = array( $subfield => $value );
            add_row( $repeater , $row, $id );
        }
        delete_post_meta( $id, 'dummy_company' );
    }