Created
August 29, 2017 13:41
-
-
Save sc0ttkclark/723898b038a819e7d83208ab20b3c143 to your computer and use it in GitHub Desktop.
Pods import csv example
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?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