The code below works flawlessly, except it will only post the first image that contains main_. I need it to pick up any column value that contains the words “main_’ thus giving me the ability to post multiple images. So if I have 3 or more main_img_url, the loop should know this and add them accordingly. I noted below where the image handler starts and ends.
Here is an example CSV:
post_title, post_content, main_img_url, main_img_url
Here is my code:
function app_csv_to_array($file = '', $delimiter = ',') {
if(!file_exists($file) || !is_readable($file))
return false;
$header = NULL;
$data = array();
if(false !== $handle = fopen($file, 'r')) {
while(false !== $row = fgetcsv($handle, 1000, $delimiter)) {
if($header)
$data[] = array_combine($header, $row);
else
$header = $row;
}
fclose($handle);
}
return $data;
}
function process($file) {
$rows = $this->app_csv_to_array($file);
foreach($rows as $row) {
$post['post_title'] = sanitize_text_field($row['post_title']);
$post['post_content'] = sanitize_text_field($row['post_content']);
$post['post_status'] = 'publish';
$post['post_author'] = 658;
$post_id = wp_insert_post($post);
//////////////// I want the loop to start here //////////////////
foreach($row as $key => $val) {
if(strstr($key, 'main_')) {
$tmp = download_url( $file );
preg_match('/[^\?]+\.(jpg|JPG|jpe|JPE|jpeg|JPEG|gif|GIF|png|PNG)/', $file, $matches);
$filename = strtolower(basename($matches[0]));
}
}
//////////////// ends here //////////////////
}
}
Your problem is inside
app_csv_to_arraymethod and specifically in thearray_combine.Based on the documentation
array_combinewill create one associative array from two input arrays having the values from the first for its keys and the values from the second for its valuesAs your keys are the headers of the
csvfile:the resulting array that will eventually be returned will have only one slot for
main_img_urlas its key.On way to circumvent this problem is to make sure that your headers in the csv file are unique, allowing at the same time the
strstr($key, 'main_')to match your columns content. Something like: