Skip to content

Instantly share code, notes, and snippets.

@dev-w3
Last active April 12, 2024 17:37
Show Gist options
  • Star 2 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save dev-w3/1d90691b777938f8238800368ab42cf7 to your computer and use it in GitHub Desktop.
Save dev-w3/1d90691b777938f8238800368ab42cf7 to your computer and use it in GitHub Desktop.
CSV Manager for WP Store Locator
<?php
#CSV Manager for WP Store Locator
#https://wordpress.org/plugins/wp-store-locator/
// Redirect to 404 if script is accessed directly
if ( ! defined("ABSPATH") ) {
header("Location: http://{$_SERVER['HTTP_HOST']}/404");
die;
};
/**
* Show insert posts button in admin backend
*/
add_action("admin_notices", function() {
echo "<div class='updated'>";
echo "<p>";
echo "To insert the store locations into the database, click the button to the right.";
echo "<a class='button button-primary' style='margin:0.25em 1em' href='{$_SERVER["REQUEST_URI"]}&insert_store_locations=1'>Insert Posts</a>";
echo "</p>";
echo "</div>";
});
/**
* Create and insert posts from CSV files
*/
add_action("admin_init", function() {
global $wpdb, $wpsl_admin;
// I'd recommend replacing this with your own code to make sure
// the post creation _only_ happens when you want it to.
if ( ! isset($_GET["insert_store_locations"]) ) {
return;
}
// Set up custom post type and custom fields. The custom fields are mapped
// to the columns defined within the CSV file. An array of column names
// will be concatenated into a single string on import.
//
// NOTE: Make sure this matches your CSV file's column names EXACTLY, i.e.
// | Name | Address1 | Address2 | Address3 | ShipAddress_City | ShipAddress_State | ShipAddress_PostalCode | Phone | Fax | Email |
// |------|-------------------|-------------------|-------------------|------------------|-------------------|------------------------|-------|-----|-------|
// | ... | ... | ... | ... | ... | ... | ... | ... | ... | ... |
// | ... | ... | ... | ... | ... | ... | ... | ... | ... | ... |
// | ... | ... | ... | ... | ... | ... | ... | ... | ... | ... |
// | ... | ... | ... | ... | ... | ... | ... | ... | ... | ... |
// | ... | ... | ... | ... | ... | ... | ... | ... | ... | ... |
$config = [
"post_type" => "wpsl_stores",
"fields" => [
"post_title" => "Name",
"wpsl_address" => "Address",
"wpsl_address2" => '',
"wpsl_city" => "City",
"wpsl_state" => "State",
"wpsl_zip" => "ZipCode",
"wpsl_country" => "United States",
"wpsl_lat" => "", // Automatically queried from Google's API if left blank
"wpsl_lng" => "", // ^^^
"wpsl_phone" => "Phone",
"wpsl_fax" => "",
"wpsl_email" => "Phone",
"wpsl_url" => "Website",
],
];
// Get the data from all those CSVs!
$posts = function() {
$data = [];
$errors = [];
// Get array of CSV files (in data/ directory in root of WP install)
$files = glob(ABSPATH . "/data/*.csv");
foreach ( $files as $file ) {
// Attempt to change permissions if not readable
if ( ! is_readable($file) ) {
chmod($file, 0744);
}
// Check if file is writable, then open it in 'read only' mode
if ( is_readable($file) && $_file = fopen($file, "r") ) {
// To sum this part up, all it really does is go row by
// row, column by column, saving all the data
$post = [];
// Get first row in CSV, which is of course the headers
$header = fgetcsv($_file);
while ( $row = fgetcsv($_file) ) {
foreach ( $header as $i => $key ) {
$post[$key] = $row[$i] !== "NULL" ? $row[$i] : null;
}
$data[] = $post;
}
fclose($_file);
} else {
$errors[] = "File '$file' could not be opened. Check the file's permissions to make sure it's readable by your server.";
}
}
if ( ! empty($errors) ) {
// ... do stuff with the errors
}
return $data;
};
// Keep count so that we don't time out
$inserted = 0;
$insert_limit = 4000;
// Look through all posts and create post in database
foreach ( $posts() as $post ) {
if ( $inserted > $insert_limit ) break;
// Populate all custom fields with content from post variable
$fields = [];
foreach ( $config["fields"] as $custom_field => $csv_column ) {
if ( is_array($csv_column) ) {
$columns = [];
foreach( $csv_column as $csv_col ) {
if ( is_null($post[$csv_col]) ) continue;
$columns[] = $post[$csv_col];
}
$fields[$custom_field] = implode(" ", $columns);
} else {
if ( array_key_exists($csv_column, $post) ) {
$fields[$custom_field] = $post[$csv_column] ?: "";
} else {
$fields[$custom_field] = $csv_column; // Default value if not in CSV
}
}
}
// If the post exists, skip this post and go to the next onne
if ( get_page_by_title($fields["post_title"], "OBJECT", $config["post_type"]) ) {
continue;
}
// Insert the post into the database
$fields["id"] = wp_insert_post([
"post_title" => $fields["post_title"],
"post_content" => "",
"post_type" => $config["post_type"],
"post_status" => "draft",
]);
// Update post's custom fields
foreach ( $fields as $field => $content ) {
// update_field($field, $content, $fields["id"]);
update_post_meta($fields["id"], $field, $content);
}
// If the address is not null, publish the post (this also fires off a
// request to Google's map API to get lat/lng)
if ( $fields["wpsl_address"] && $fields["wpsl_city"] && $fields["wpsl_zip"] ) {
// Get lat/long
$wpsl_admin->geocode->check_geocode_data($fields["id"], [
"lat" => $fields["wpsl_lat"],
"lng" => $fields["wpsl_lng"],
"address" => $fields["wpsl_address2"],
"city" => $fields["wpsl_city"],
"zip" => $fields["wpsl_zip"],
"country" => $fields["wpsl_country"],
]);
wp_publish_post($fields["id"]);
}
$inserted++;
}
});
@zeus1921
Copy link

zeus1921 commented Jul 7, 2021

hey man.
It's not importing correctly can you update it for the new version?

@dev-w3
Copy link
Author

dev-w3 commented Jul 21, 2021

hey man.
It's not importing correctly can you update it for the new version?

Can you please explain the issue, are you not able to import the data?

@sam247
Copy link

sam247 commented Jan 19, 2024

Hey man - is this still working? How do you import it?

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment