Skip to content

Instantly share code, notes, and snippets.

@conkonig
Created April 13, 2020 23:43
Show Gist options
  • Save conkonig/10dda7fb420ca27b5349b756d08988ee to your computer and use it in GitHub Desktop.
Save conkonig/10dda7fb420ca27b5349b756d08988ee to your computer and use it in GitHub Desktop.
Bulk Importing tags and assigning to wordpress posts from csv file
<?php
class CsvImporter
{
private $fp;
private $parse_header;
private $header;
private $delimiter;
private $length;
//--------------------------------------------------------------------
function __construct($file_name, $parse_header = false, $delimiter = "\t", $length = 8000)
{
$this->fp = fopen($file_name, "r");
$this->parse_header = $parse_header;
$this->delimiter = $delimiter;
$this->length = $length;
// $this->lines = $lines;
if ($this->parse_header) {
$this->header = fgetcsv($this->fp, $this->length, $this->delimiter);
}
}
//--------------------------------------------------------------------
function __destruct()
{
if ($this->fp) {
fclose($this->fp);
}
}
//--------------------------------------------------------------------
function get($max_lines = 0)
{
//if $max_lines is set to 0, then get all the data
$data = array();
if ($max_lines > 0)
$line_count = 0;
else
$line_count = -1; // so loop limit is ignored
while ($line_count < $max_lines && ($row = fgetcsv($this->fp, $this->length, $this->delimiter)) !== FALSE) {
if ($this->parse_header) {
foreach ($this->header as $i => $heading_i) {
$row_new[$heading_i] = $row[$i];
}
$data[] = $row_new;
} else {
$data[] = $row;
}
if ($max_lines > 0)
$line_count++;
}
return $data;
}
//--------------------------------------------------------------------
}
?>
<?php
echo 'Adding tags \n Check for errors in the output after import.';
$importer = new CsvImporter(get_template_directory() . '/tags.csv', true, ",");
$data = $importer->get();
// $test = array_shift($data);
$results = array();
foreach ($data as $row) {
$postID = $row['id'];
if ($row['tags']) {
$tags = explode('|', $row['tags']);
$termsToAttach = array();
foreach ($tags as $tag) {
if ($tag) {
$existingTag = get_term_by('name', $tag, 'post_tag');
if (!$existingTag) {
$newTag = wp_insert_term(
$tag,
'post_tag',
array(
'description' => '',
'slug' => createSlug($tag),
)
);
$existingTag = get_term_by('id', $newTag['term_id'], 'post_tag');
}
$tagID = (int) $existingTag->term_id;
array_push($termsToAttach, $tagID);
}
}
$result = wp_set_post_terms($postID, $termsToAttach, 'post_tag', true);
array_push($results, $result);
}
}
var_export($result);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment