File: /home/axxoncom/domains/spatialtrek.us/public_html/wp-content/plugins/csv-importer/csv-importer.php
<?php
/*
Plugin Name: CSV Importer
Description: A simple plugin to import data from CSV files.
Version: 1.0
Author: Your Name
*/
if (!defined('ABSPATH')) {
exit; // Exit if accessed directly
}
// Add an admin menu for the CSV Importer
add_action('admin_menu', 'csv_importer_add_menu');
function csv_importer_add_menu() {
add_menu_page(
'CSV Importer',
'CSV Importer',
'manage_options',
'csv-importer',
'csv_importer_admin_page',
'dashicons-upload',
20
);
}
// Display the admin page for CSV Importer
function csv_importer_admin_page() {
if (!current_user_can('manage_options')) {
return;
}
echo '<div class="wrap">';
echo '<h1>CSV Importer</h1>';
if (isset($_POST['submit_csv'])) {
if (isset($_FILES['csv_file']) && $_FILES['csv_file']['error'] === UPLOAD_ERR_OK) {
$csv_file = $_FILES['csv_file']['tmp_name'];
$result = csv_importer_process_file($csv_file);
if ($result) {
echo '<div class="updated"><p>CSV imported successfully!</p></div>';
} else {
echo '<div class="error"><p>Failed to import CSV.</p></div>';
}
} else {
echo '<div class="error"><p>Please upload a valid CSV file.</p></div>';
}
}
echo '<form method="post" enctype="multipart/form-data">';
echo '<input type="file" name="csv_file" accept=".csv" required />';
echo '<input type="submit" name="submit_csv" class="button-primary" value="Import CSV" />';
echo '</form>';
echo '</div>';
}
// Process the uploaded CSV file
function csv_importer_process_file($csv_file) {
if (!file_exists($csv_file) || !is_readable($csv_file)) {
return false;
}
$data = [];
$header = null;
if (($handle = fopen($csv_file, 'r')) !== false) {
while (($row = fgetcsv($handle, 1000, ',')) !== false) {
if (!$header) {
$header = $row;
} else {
$data[] = array_combine($header, $row);
}
}
fclose($handle);
}
if (!empty($data)) {
foreach ($data as $row) {
// Example: Insert data into a custom post type or table
wp_insert_post([
'post_type' => 'post', // Change to your desired post type
'post_title' => $row['Title'], // Adjust for your CSV headers
'post_content' => $row['Content'], // Adjust for your CSV headers
'post_status' => 'publish'
]);
}
return true;
}
return false;
}