Skip to content

Instantly share code, notes, and snippets.

@sc0ttkclark
Created August 29, 2017 13:41
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 sc0ttkclark/723898b038a819e7d83208ab20b3c143 to your computer and use it in GitHub Desktop.
Save sc0ttkclark/723898b038a819e7d83208ab20b3c143 to your computer and use it in GitHub Desktop.
Pods import csv example
<?php
/**
* Import CSV example for Pods
*
* @param string $file File location
*
* @return true|WP_Error Returns true on success, WP_Error if there was a problem
*/
function my_import_csv( $file ) {
if ( ! is_readable( $file ) ) {
return new WP_Error( '', sprintf( 'Can\'t read file: %', $file ) );
}
if ( ! function_exists( 'pods_migrate' ) ) {
return new WP_Error( '', 'pods_migrate function not found' );
}
/**
* @var $migrate \PodsMigrate
*/
$migrate = pods_migrate();
$contents = file_get_contents( $file );
$parsed_data = $migrate->parse_sv( $contents, ',' );
$pod = pods( 'your_pod' ); // @todo Update to your pod name
if ( ! empty( $parsed_data['items'] ) ) {
$total_found = count( $parsed_data['items'] );
foreach ( $parsed_data['items'] as $row ) {
// Do what you want with $row
// $row has the column names from the first row of the CSV
// Example: $row['column heading 1']
// Example: $row['user_email']
$data = array(
'some_field' => $row['some_field'],
);
$new_item_id = $pod->add( $data );
}
} else {
return new WP_Error( '', 'No items to import.' );
}
return true;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment