Skip to content

Instantly share code, notes, and snippets.

@certainlyakey
Last active August 29, 2015 14:05
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save certainlyakey/a6197d5ada598367996e to your computer and use it in GitHub Desktop.
Save certainlyakey/a6197d5ada598367996e to your computer and use it in GitHub Desktop.
Wordpress - import post connections from CSV file (with RS CSV Importer and Posts 2 Posts plugins)
<?php
/*
Plugin Name: Replace save_post method of Really Simple CSV Importer (customized)
Description: This is an example add-on.
Author: Takuro Hishikawa,
Version: 0.2
*/
class rscsvimporter_replace_save_post {
// singleton instance
private static $instance;
public static function instance() {
if ( isset( self::$instance ) )
return self::$instance;
self::$instance = new rscsvimporter_replace_save_post;
self::$instance->run_init();
return self::$instance;
}
public function __construct() {
/** Do nothing **/
}
protected function run_init() {
add_action( 'init', array( $this, 'add_filter' ) );
}
public function add_filter() {
add_filter( 'really_simple_csv_importer_class', array( $this, 'return_class'));
}
public function return_class() {
return get_class($this);
}
public function save_post($post, $meta, $terms, $thumbnail, $is_update) {
if (!class_exists('wp_post_helper',false)) {
return false;
}
$ph = new wp_post_helper($post);
foreach ($meta as $key => $value) {
// Add custom field if the given key already exists.
// The default of third variable in Really Simple CSV Importer is true
$ph->add_meta($key, $value, true);
}
foreach ($terms as $key => $value) {
$ph->add_terms($key, $value);
}
if ($thumbnail) $ph->add_media($thumbnail,'','','',true);
if ($is_update)
$result = $ph->update();
else
$result = $ph->insert();
// Custom code below
//connected posts' slugs are delimited with ';' and imported as custom field in separate column with 'sudexmb_regs_specs' header
if ($result) {
global $wpdb;
if (isset($meta['sudexmb_regs_specs'])) {
$spec_slugs = explode(';',$meta['sudexmb_regs_specs']);
$debugtext = '';
foreach ($spec_slugs as $spec_slug) {
$spec_slug = preg_replace('/\./','-', $spec_slug);
$spec_id = $wpdb->get_var("SELECT ID FROM $wpdb->posts WHERE post_name = '$spec_slug' AND post_type = 'speciality'");
//$debugtext = $debugtext.' // found spec slug:'.$spec_slug.'; post ID: '.$ph->postid().'; spec id:'.$spec_id;
//$ph->add_meta('sudexmb_regs_specs', $debugtext, true);
if ($spec_id) {
p2p_type( 'specialities_to_registry' )->connect( $spec_id, $ph->postid(), array(
'date' => current_time('mysql')
) );
}
}
}
}
unset($ph);
return $result;
}
}
$rscsvimporter_replace_save_post = rscsvimporter_replace_save_post::instance();
@hissy
Copy link

hissy commented Aug 16, 2014

👍

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