I have been stuck for a little while on this, so am hoping someone can help me.
The principle of what i am trying to achieve is:
Open CSV
Check existing posts if a field with a value from CSV exists.
If it exists then to update it
Else Insert the post
This is the code that i already have, however i most probably have over complicated it.
<?php
function auto_import() {
global $wpdb;
$vehicles = get_posts( array( 'post_type' => 'vehicle', 'numberposts' => -1, 'post_status' => 'any'));
if (($handle = fopen($_SERVER['DOCUMENT_ROOT'].'vehicles.csv', "r")) !== FALSE) {
while (($import = fgetcsv($handle, 10000, ",")) !== FALSE) {
if($row == 1){ $row++; continue; }
$csv_vrm = $import[4];
foreach($vehicles as $vehicle) {
$vrm = get_field('field_5b435f456789j', $vehicle->ID);
$insert_array = insertVRM($vehicle, $csv_vrm, $vrm, $make, $model, $derivative, $registration);
$update_array = updateVRM($vehicles, $csv_vrm, $vrm);
}
print_r($insert_array);
print_r($update_array);
}
}
}
function insertVRM($vehicle, $csv_vrm, $vrm, $make, $model, $derivative, $registration) {
$insert_array = array();
if(($csv_vrm !== $vrm) || empty($vrm) ) {
$post_id = wp_insert_post( array(
'post_title' => $vrm,
'post_name' => uniqid(). '-' . $vrm,
'post_type' => 'vehicle',
'post_status' => 'publish',
'comment_status' => 'closed',
));
update_field('field_5b435f456789j', $registration, $post_id);
$insert_array[] = $csv_vrm;
echo "Added " . $csv_vrm . " to insert";
}
return $insert_array;
}
function updateVRM($vehicles, $csv_vrm, $vrm) {
$update_array = array();
if($csv_vrm === $vrm) {
echo 'Both Matched <br/>';
$update_array[] = $csv_vrm;
echo "Added " . $csv_vrm . " to update";
}
return $update_array;
}
The Foreach loop foreach($vehicles as $vehicle) is to loop through the existing posts.
I am open to any suggestions and hope someone can help!
Aucun commentaire:
Enregistrer un commentaire