Skip to content

Instantly share code, notes, and snippets.

@MogulChris
Created March 27, 2022 22:07
Show Gist options
  • Save MogulChris/6a5bd022a1fdc3bca629d7b891c8b076 to your computer and use it in GitHub Desktop.
Save MogulChris/6a5bd022a1fdc3bca629d7b891c8b076 to your computer and use it in GitHub Desktop.
Basic csv export for WP Store Locator
<?php
//bootstrap WP
require_once('wp-load.php');//I have this file saved in the site root
$stores = get_posts([
'post_type' => 'wpsl_stores',
'posts_per_page' => -1,
'post_status' => 'any'
]);
if(!empty($stores)){
$output = [];
$headings = ['title','categories','wpsl_address','wpsl_address2','wpsl_city','wpsl_state','wpsl_zip','wpsl_country','wpsl_lat','wpsl_lng','wpsl_phone','wpsl_email','wpsl_fax','wpsl_url','wpsl_country_iso','wpsl_hours','show_at_checkout'];
$output[] = $headings;
foreach($stores as $store){
$row = [];
$meta = get_post_meta($store->ID);
foreach($headings as $key){
if($key == 'title'){
$row[$key] = $store->post_title;
}
elseif($key == 'categories'){
$cats = wp_get_object_terms($store->ID,'wpsl_store_category');
if(!empty($cats) && !is_wp_error($cats)){
$cat_names = array_map(function($cat){
return $cat->name;
},$cats);
$cat_names = implode('|', $cat_names);
}
else{ $cat_names = ''; }
$row[$key] = $cat_names;
}
elseif($key == 'wpsl_hours'){
$hours = unserialize($meta[$key][0]);
$row[$key] = !empty($meta[$key][0]) ? json_encode($hours) : '';//JSON is easier to read, I will need to convert this back when importing
}
else{
$row[$key] = $meta[$key][0];
}
}
$output[] = $row;
}
header("Content-Type: text/csv");
header("Content-Disposition: attachment; filename=stores" . time() . ".csv");
$outstream = fopen("php://output", 'w');
function __outputCSV(&$vals, $key, $filehandler) {
fputcsv($filehandler, $vals, ',', '"');
}
array_walk($output, '__outputCSV', $outstream);
fclose($outstream);
}//if()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment