Skip to content

Instantly share code, notes, and snippets.

@brandonbarringer
Last active August 6, 2019 19:45
Show Gist options
  • Save brandonbarringer/725d070d7da30fbf93f605922d8c2bf9 to your computer and use it in GitHub Desktop.
Save brandonbarringer/725d070d7da30fbf93f605922d8c2bf9 to your computer and use it in GitHub Desktop.
Recategorizes Posts from data in CSV
<?php
// @Description
// Creates and assigns categories to a list of post URLs via a CSV file
// If we have a file to parse
if ( ($handle = fopen( get_stylesheet_directory() . "/categories.csv", "r" ) ) !== FALSE ) {
// While we are parsing the CSV
// Every iteration is 1 row
// @example fgetcsv($handle, $max_length, $delimiter)
// @url http://php.net/manual/en/function.fgetcsv.php
while ( ( $data = fgetcsv( $handle, 2000, "," ) ) !== FALSE ) {
// Get url from column 1
$url = $data[0];
// Change url to ID
// @url https://codex.wordpress.org/Function_Reference/url_to_postid
$post_ID = url_to_postid( $url );
// Put new categories strings in Array from Column2
// Categories are formated cat1|cat2|cat3|etc...
$str_cats = preg_split( "/\|/", $data[1] );
// Create and array to hold our cat IDs
$new_cats = array();
// For every item in our array of category strings
for ( $i = 0, $count = count( $str_cats ); $i < $count; $i++ ) {
// If the category doesn't already exist
if ( !is_category( $str_cats[$i] ) ) {
// Create the new Cat in WP
// @example wp_create_category( int $cat_ID );
wp_create_category( $str_cats[$i] );
}
// Add category IDs from category string to array using get_cat_ID
// @example get_cat_ID( str $cat_str );
// @url https://codex.wordpress.org/Function_Reference/get_cat_ID
$new_cats[] = get_cat_ID( $str_cats[$i] );
}
// Set our Categories
// @example wp_set_post_categories( int $post_ID, arr $cat_ID, bool $append );
// @url https://codex.wordpress.org/Function_Reference/wp_set_post_categories
wp_set_post_categories( $post_ID, $new_cats, FALSE );
}
// Close the file so our While loop returns false
fclose( $handle );
}
?>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment