Skip to content

Instantly share code, notes, and snippets.

@sabrina-zeidan
Created July 22, 2017 14:59
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save sabrina-zeidan/2bdf712e24a3e19bf478442047f8143d to your computer and use it in GitHub Desktop.
Save sabrina-zeidan/2bdf712e24a3e19bf478442047f8143d to your computer and use it in GitHub Desktop.
Bulk delete tags with no posts (posts only check, may probable have cpt attached) [Wordpress]
function delete_tags_with_no_posts(){
$tags = get_tags( array('number' => 0,'hide_empty' => false));
foreach ( $tags as $tag ) {
$tag_id = $tag->term_id;
$args = array( 'post_type' => 'post', 'posts_per_page' => -1,
'tax_query' => array(
array(
'taxonomy' => 'post_tag',
'field' => 'id',
'terms' => $tag_id
)
)
);
$postslist = get_posts( $args );
$count_posts_with_this_tag = count($postslist);
if ($count_posts_with_this_tag < 1 ){
wp_delete_term( $tag_id, 'post_tag' );
}
}
}
add_action( 'wp_head', 'delete_tags_with_no_posts' );
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment