Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Save developer-anuragsingh/e309d49e0fe1ea84b0071663bba39302 to your computer and use it in GitHub Desktop.
Save developer-anuragsingh/e309d49e0fe1ea84b0071663bba39302 to your computer and use it in GitHub Desktop.
WP - Update post's taxonomy terms and slug programmatically (PHP, Wordpress)
// List of post need to modify.
// $posts = array(
// array(
// 'id' => 1,
// 'term' => get_term_id_by_name(array('parent', 'child')),
// 'taxonomy' => 'category',
// ),
// array(
// 'id' => 5,
// 'term' => get_term_id_by_name(array('parent')),
// 'taxonomy' => 'category',
// ),
// );
// Fetch list of array from given .csv file
$rows = array_map('str_getcsv', file('FILE_PATH/file.csv'));
$header = array_shift($rows);
$posts = array();
foreach ($rows as $row) {
$posts[] = array_combine($header, $row);
}
// Fetch term id from given term name.
function get_term_id_by_name($terms, $taxonomy = 'category', $parent = '')
{
foreach ($terms as $term) {
$term_id = term_exists($term, $taxonomy, $parent);
$term_id_arr[] = $term_id['term_taxonomy_id'];
}
return $term_id_arr;
}
// Add terms in existing posts.
$run = 1;
if ($run == 1) {
foreach ($posts as $post) {
$post_id = $post['ID'];
$post_name = sanitize_title($post['post_name']);
$terms = get_term_id_by_name(explode(', ', $post['terms']));;
$taxonomy = $post['taxonomy'];
$updated_posts = wp_set_post_terms($post_id, $terms, $taxonomy, $appended_in_existing_tags = false);
// ** Check If Page does not exist, if true, create a new post
if (False !== get_post_status($post_id)) {
// Update the post into the database
$updated_post_id = wp_update_post(
array(
'ID' => $post_id,
'post_name' => $post_name
)
);
if (is_wp_error($updated_post_id)) {
$errors = $updated_post_id->get_error_messages();
foreach ($errors as $error) {
echo $error;
}
}
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment