Skip to content

Instantly share code, notes, and snippets.

@vodanh1213
Last active August 29, 2015 14:14
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save vodanh1213/0473689440304441cdb7 to your computer and use it in GitHub Desktop.
Save vodanh1213/0473689440304441cdb7 to your computer and use it in GitHub Desktop.
<?php
/*
* Plugin Name: Marketpress csv converter
Author: Hoang
Version: 1.0
*/
add_action('admin_menu', 'mpc_admin_menu');
function mpc_admin_menu()
{
add_menu_page('MarketPress CSV', 'MarketPress CSV', 'manage_options', 'mpc-main', 'convert_csv_to_mp');
}
function convert_csv_to_mp()
{
if (isset($_POST['submit_csv'])) {
if (isset($_FILES['csv']) && !empty($_FILES['csv']['name'])) {
$file = mpc_convert_csv($_FILES['csv']['tmp_name']);
echo 'You can download your file <a download="" href="' . plugin_dir_url(__FILE__) . $file . '">here</a>';
} else {
echo 'Please upload a csv file';
}
}
?>
<div class="wrap">
<h2>Convert CSV to MP format</h2>
<form method="post" enctype="multipart/form-data">
<input type="file" name="csv">
<button name="submit_csv" type="submit">Submit</button>
</form>
</div>
<?php
}
function mpc_import_to_mp()
{
//Update this variable to your need
$raw_file_path = plugin_dir_path(__FILE__) . 'sampleCSV.csv';
$converted_file_path = mpc_convert_csv($raw_file_path);
$importer = new CsvImporterFork();
$importer->process(plugin_dir_path(__FILE__) . $converted_file_path);
}
function mpc_convert_csv($csv_path)
{
//$csv_path = plugin_dir_path(__FILE__) . 'sampleCSV.csv';
$csvData = file_get_contents($csv_path);
$lines = explode(PHP_EOL, $csvData);
$array = array();
foreach ($lines as $line) {
$array[] = str_getcsv($line, ";");
}
//restruct the csv
$header = array_shift($array);
$products = array();
$array = array_filter($array);
foreach ($array as $row) {
if (count($row) == count($header)) {
$products[] = array_combine($header, $row);
}
}
//got the array, convert to MP csv
$mp_convert = array();
foreach ($products as $prod) {
$mp_convert[] = array(
'title' => $prod['Label'],
'description' => $prod['Description'],
'sku' => $prod['SKU'],
'price' => $prod['Price'],
'sale_price' => '',
'tags' => $prod['Brand'],
'categories' => $prod['Category'],
'stock' => '',
'external_link' => '',
'download_url' => '',
'sales_count' => '',
'extra_shipping' => $prod['Delivery'],
'weight' => $prod['Weight'],
'image' => $prod['Picture']
);
}
//add header
if (count($mp_convert)) {
$header = array_keys($mp_convert[0]);
//flat
/*foreach ($mp_convert as &$row) {
$row = implode(',', $row);
}*/
$mp_convert = array_merge(array($header), $mp_convert);
$cv_file = time() . '_converted.csv';
//var_dump($mp_convert);
//create csv file
$fp = fopen(plugin_dir_path(__FILE__) . $cv_file, 'w');
foreach ($mp_convert as $row) {
fputcsv($fp, $row, ";");
}
fclose($fp);
return $cv_file;
}
}
if (!class_exists('MarketPress_Importer')) {
$path = $dir = ABSPATH . 'wp-content/plugins/';
require_once $path . 'marketpress/marketpress-includes/marketpress-importers.php';
}
class CsvImporterFork extends MarketPress_Importer
{
var $importer_name = 'CSV';
function process($path)
{
global $wpdb;
set_time_limit(120); //this can take a while
$this->results = 0;
$products = $this->get_csv_array($path);
$dirs = wp_upload_dir();
foreach ($products as $row) {
$product = array();
if (empty($row['title']) || (empty($row['price']) && MP_IMPORT_ALLOW_NO_PRICE === false))
continue;
//import product
$product['post_title'] = $row['title'];
$product['post_content'] = $row['description'];
$product['post_type'] = 'product';
$product['comment_status'] = 'closed';
$product['comment_count'] = 0;
/**
* Filter the imported post status
*
* @since 2.9.5.5
* @param string The default post status - e.g. "draft"
*/
$product['post_status'] = apply_filters('mp_imported_product_post_status', 'draft');
//add tags
if (!empty($row['tags']))
$product['tax_input']['product_tag'] = trim($row['tags']);
$new_id = wp_insert_post($product); //create the post
//insert categories
if (!empty($row['categories'])) {
$product_cats = explode(',', trim($row['categories']));
$product_cats = array_map('trim', $product_cats);
wp_set_object_terms($new_id, $product_cats, 'product_category');
}
//add product meta
update_post_meta($new_id, 'mp_sku', array(preg_replace("/[^a-zA-Z0-9_-]/", "", trim(@$row['sku'])))); //add sku
update_post_meta($new_id, 'mp_price', array(round((float)preg_replace('/[^0-9.]/', '', $row['price']), 2))); //add price
update_post_meta($new_id, 'mp_var_name', array('')); //add blank var name
//add sale price only if set
if (!empty($row['sale_price'])) {
update_post_meta($new_id, 'mp_is_sale', 1);
update_post_meta($new_id, 'mp_sale_price', array(round((float)preg_replace('/[^0-9.]/', '', $row['sale_price']), 2)));
update_post_meta($new_id, 'mp_price_sort', round((float)preg_replace('/[^0-9.]/', '', $row['sale_price']), 2));
} else {
update_post_meta($new_id, 'mp_is_sale', 0);
update_post_meta($new_id, 'mp_price_sort', round((float)preg_replace('/[^0-9.]/', '', $row['price']), 2));
}
//add stock count if set
if (is_numeric($row['stock'])) {
update_post_meta($new_id, 'mp_track_inventory', 1);
update_post_meta($new_id, 'mp_inventory', array(intval($row['stock'])));
} else {
update_post_meta($new_id, 'mp_track_inventory', 0);
}
//add external link
if (!empty($row['external_link']))
update_post_meta($new_id, 'mp_product_link', esc_url_raw($row['external_link']));
//add shipping info
$shipping = array();
if (!empty($row['extra_shipping']))
$shipping['extra_cost'] = round((float)preg_replace('/[^0-9.]/', '', $row['extra_shipping']), 2);
if (!empty($row['weight']))
$shipping['weight'] = round((float)preg_replace('/[^0-9.]/', '', $row['weight']), 2);
update_post_meta($new_id, 'mp_shipping', $shipping);
//download
if (!empty($row['download_url']))
update_post_meta($new_id, 'mp_file', esc_url_raw($row['download_url']));
//download
if (isset($row['sales_count']))
update_post_meta($new_id, 'mp_sales_count', intval($row['sales_count']));
//add featured images
if (isset($row['image']) && !empty($row['image'])) {
// Determine if this file is in our server
$img_location = '/' . str_replace($dirs['baseurl'], $dirs['basedir'], $row['image']); // make sure this is a path and not a url
$img_location = str_replace('//', '/', $img_location); // remove double slashes - just in case
if (false === strpos($img_location, $dirs['basedir'])) {
$img_location_rel = $img_location;
$img_location_abs = $dirs['basedir'] . $img_location;
} else {
$img_location_rel = str_replace($dirs['basedir'], '', $img_location);
$img_location_abs = $img_location;
}
$img_location_rel = ltrim($img_location_rel, '/');
// Check if image exists in database
$cache_key = md5($row['image']);
$attachment_id = wp_cache_get($cache_key, 'mp_csv_importer');
if (false === $attachment_id) {
$attachment_id = $wpdb->get_var($wpdb->prepare("
SELECT post_id
FROM $wpdb->postmeta
WHERE meta_key = '_wp_attached_file'
AND meta_value = %s
LIMIT 1", $img_location_rel
));
}
if ($attachment_id) {
update_post_meta($new_id, '_thumbnail_id', $attachment_id);
} elseif (file_exists($img_location_abs)) {
preg_match('/[^\?]+\.(jpe?g|jpe|gif|png)\b/i', $img_location_abs, $matches);
$file_array = array(
'name' => basename($matches[0]),
'tmp_name' => $img_location_abs,
);
// Attach image to post
$attachment_id = media_handle_sideload($file_array, $new_id, $row['title']);
if (!is_wp_error($attachment_id)) {
// add featured image to post
update_post_meta($new_id, '_thumbnail_id', $attachment_id);
}
} else { //download the image and attach
require_once(ABSPATH . '/wp-admin/includes/file.php');
$img_html = media_sideload_image($row['image'], $new_id, $row['title']);
if (!is_wp_error($img_html)) {
//figure out the id
$args = array(
'numberposts' => 1,
'order' => 'DESC',
'post_mime_type' => 'image',
'post_parent' => $new_id,
'post_type' => 'attachment'
);
$get_children_array = get_children($args, ARRAY_A); //returns Array ( [$image_ID]...
$rekeyed_array = array_values($get_children_array);
$child_image = $rekeyed_array[0];
$attachment_id = $child_image['ID'];
// add featured image to post
update_post_meta($new_id, '_thumbnail_id', $attachment_id);
wp_cache_set($cache_key, $attachment_id, 'mp_csv_importer');
}
}
wp_cache_set($cache_key, $attachment_id, 'mp_csv_importer');
}
//inc count
$this->results++;
}
}
function get_csv_headers($file_path)
{
@ini_set('auto_detect_line_endings', true); //so it doesn't choke on mac CR line endings
$fh = @fopen($file_path, 'r');
if ($fh) {
$temp_fields = fgetcsv($fh, 5120, ";"); // 5KB
if (is_array($temp_fields))
$headers = array_map('strtolower', $temp_fields);
fclose($fh);
return $headers;
} else {
return false;
}
}
function get_csv_array($file_path)
{
$i = 0;
@ini_set('auto_detect_line_endings', true); //so it doesn't choke on mac CR line endings
$fh = @fopen($file_path, 'r');
if ($fh) {
while (!feof($fh)) {
//parse csv line
$temp_fields = fgetcsv($fh, 5120, ";"); // 5KB
if (is_array($temp_fields)) {
if (!isset($titles))
$titles = array_map('strtolower', $temp_fields);
//switch keys out for titles
$new_fields = array();
foreach ($temp_fields as $key => $value) {
$new_fields[$titles[$key]] = $value;
}
$fields[] = $new_fields;
}
}
fclose($fh);
//remove header row
array_shift($fields);
return $fields;
} else {
return false;
}
}
}
@Richard-WebVortex
Copy link

Last weekend I added a $factor variable in mpc_convert_csv(), and set it to 1.1 for testing purposes.

I also edited line 73:
'price' => strval(round(floatval($prod['Price']) * $factor, 2)),

and I also edited line 75:
'tags' => $prod['Brand'] . "," . $prod['Market'] . "," . $prod['Segment'],

I tested this, and foud it to be working. However, I don't think the import function is called.

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