Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
[Really Simple CSV Importer] add-on: Update row based on a custom field ID/key match
<?php
/*
Plugin Name: Update row based on a custom field ID/key match
Plugin URI: https://wordpress.org/support/topic/update-row-based-on-a-custom-field-idkey-match
*/
add_filter('really_simple_csv_importer_class', function() {
return "ImporterCustomize";
});
class ImporterCustomize
{
public function save_post($post,$meta,$terms,$thumbnail,$is_update)
{
/* Start customization */
// Get the identifier meta value
$sku_value = $meta['SKU'];
// Get a matched post by meta value
$args = array(
'post_type' => 'post',
'post_status' => 'any',
'meta_query' => array(
array(
'key' => 'SKU',
'value' => $sku_value,
'compare' => '=',
'cache_results' => false,
'suppress_filters' => true
)
)
);
$query = new WP_Query( $args );
if ( $query->have_posts() ) {
$original_post = $query->next_post();
// Add ID value for replacement post data
$post['ID'] = $original_post->ID;
$is_update = true;
}
/* End customization */
/* ///////////////// */
/* Copied from RS_CSV_Importer#save_post */
// Separate the post tags from $post array
if (isset($post['post_tags']) && !empty($post['post_tags'])) {
$post_tags = $post['post_tags'];
unset($post['post_tags']);
}
// Add or update the post
if ($is_update) {
$h = RSCSV_Import_Post_Helper::getByID($post['ID']);
$h->update($post);
} else {
$h = RSCSV_Import_Post_Helper::add($post);
}
// Set post tags
if (isset($post_tags)) {
$h->setPostTags($post_tags);
}
// Set meta data
$h->setMeta($meta);
// Set terms
foreach ($terms as $key => $value) {
$h->setObjectTerms($key, $value);
}
// Add thumbnail
if ($thumbnail) {
$h->addThumbnail($thumbnail);
}
return $h;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.