Code Samples: Import CSV Example - Pods Docs
Mon Nov 27 2023 19:42:55 GMT+0000 (Coordinated Universal Time)
Saved by
@dmsearnbit
<?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;
}
content_copyCOPY
https://docs.pods.io/code-snippets/import-csv-example/
Comments