Skip to content

Instantly share code, notes, and snippets.

@tiagonoronha
Created August 31, 2020 15:12
Show Gist options
  • Save tiagonoronha/4b7cec786f050514509123f28a663c12 to your computer and use it in GitHub Desktop.
Save tiagonoronha/4b7cec786f050514509123f28a663c12 to your computer and use it in GitHub Desktop.
MAPS add tags to posts
<?php
$lines = file( dirname(__FILE__) . '/tags.csv', FILE_SKIP_EMPTY_LINES | FILE_IGNORE_NEW_LINES );
foreach ( $lines as $line ) {
$line = str_getcsv( $line );
// Vars.
$search_term = $line[0];
$tags = explode( '|', $line[1] );
$args = array(
's' => $search_term,
'post_type' => 'post',
'post_status' => 'any',
'posts_per_page' => -1,
'fields' => 'ids',
);
$posts = get_posts( $args );
foreach ( $posts as $post ) {
foreach ( $tags as $tag ) {
$term_id = false;
$term = get_term_by( 'slug', sanitize_title( $tag ), 'post_tag' );
if ( $term ) {
$term_id = (int) $term->term_id;
} else {
$new_tag = wp_insert_term(
$tag, // the term
'post_tag', // the taxonomy
array(
'slug' => sanitize_title( $tag )
)
);
if ( ! is_wp_error( $new_tag ) ) {
$term_id = (int) $new_tag['term_id'];
}
}
if ( false !== $term_id ) {
wp_set_object_terms( $post, array( $term_id ), 'post_tag', true );
}
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment