Skip to content

Instantly share code, notes, and snippets.

@NickGreen
Forked from tiagonoronha/maps_tags.php
Last active September 22, 2020 22:47
Show Gist options
  • Save NickGreen/554e4506a1d098f4229231c9a38fc325 to your computer and use it in GitHub Desktop.
Save NickGreen/554e4506a1d098f4229231c9a38fc325 to your computer and use it in GitHub Desktop.
MAPS add tags to posts - wrapped in CLI command
<?php
class MAPS_Tags extends WP_CLI_COMMAND {
function __invoke() {
$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];
if ( "Search Term" == $search_term ) {
echo 'skipping first row' . "\n";
continue;
}
$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 );
echo 'Posts: ';
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'];
echo 'New tag created: ' . $tag . "\n";
}
}
if ( false !== $term_id ) {
wp_set_object_terms( $post, array( $term_id ), 'post_tag', true );
echo 'Tag ' . $tag . ' added to post ID ' . $post . "\n";
}
}
}
}
}
}
WP_CLI::add_command( 'maps-tags', 'MAPS_Tags' );
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment