Search code examples
phpexcelwpallimport

Import multiple custom field values from single CSV entry


My data in the database is stored in this format as an array.

The correct way of storing:

array (
  0 => '18459',
  1 => '18462',
)

The format for importing is separated by a pipe in my csv file like so 18459|18461 but whenever I import, it instead stores the values like this.

array (
  0 => '18459|18461',
)

[Additional Info] This is how the database stores the data by duplicating the meta key sp_team. If I can change the second meta key to something else say sp_team2 then have that in my CSV file I think it might work. The problem is that my import thinks it should just import both 18459|18462 into just one sp_team field and that the other sp_team is not needed which is not the case. But I don't know how.

enter image description here

Inside the wp-editor for the two fields

enter image description here If there was a way I can rename the second sp_team that would work?

I am desperate for a workaround. As you can see, it's not storing the second value. I'll appreciate your help. Thanks


Solution

  • You can break up the values inside a hook and insert them one by one.

    This needs to go into the functions.php file of the active theme (or child theme). Commented inline for clarity.

    function my_18459_update_post_meta( $post_id, $meta_key, $meta_value ) {
        $separator = '|';
    
        // only act on the 2 custom fields with pipes as separators:
        if($meta_key == 'sp_team' || $meta_key == 'sp_player') {
    
            /* Hook fires AFTER the "incorrect" unseparated meta value was 
               inserted in the DB, so need to delete it first: */
            delete_post_meta($post_id, $meta_key, $meta_value);
    
            // break up the values using | as separator:
            $meta_values = explode($separator, $meta_value);
            if ( ! empty( $meta_values ) ) {
                // insert values into wp_postmeta table one by one:
                foreach ( $meta_values as $meta_value ) {
                    add_post_meta($post_id, $meta_key, $meta_value);
                }
            }
        }
    }
    
    add_action( 'pmxi_update_post_meta', 'my_18459_update_post_meta', 10, 3 );
    

    Screenshots of relevant import settings I used:

    screenshot of WP All Import custom fields setting

    screenshot of WP All Import record matching setting

    You can also check the import settings at the link you provided in the comments.