Alex Alex - 3 months ago 9
MySQL Question

Delete wp tags from an array correctly

I need to remove some tags periodically from my wp table. Right now I'm using this:

DELETE FROM wp_terms WHERE slug = 'tag-to-delete';


But I suppose that the way I'm doing this is not correct because I think I must delete also all the relations with the term, right?

Besides, I would need to do this via functions.php by placing the tags inside an array. eg:
$tags_to_delete = tag1, tag2, tag3;


Is it possible to do this via functions.php? If so, can someone explain me the correct way to do it?

EDITED: I've managed this solution, but this may not be the final solution because I still have some questions:


  1. Is this safe to use?

  2. Is the query correct or it can be improved?

  3. Is there a way to return the number of deleted tags?

  4. Is there any other way to do this?



Please see my solution bellow and help making a better answer to this question.

Answer

OK! I got this working and I hope this can be useful to anyone else. Still, I have some questions:

  1. Is this safe to use?
  2. Is the query correct or it can be improved?
  3. Is there a way to return the number of deleted tags?
  4. Is there any other way to do this?

    $all_terms = array( 'tag number one', 'tag number two', );
    
    foreach ( $all_terms as $term ) {
    $terms = $wpdb->get_row( "SELECT t.*, tt.* FROM $wpdb->terms AS t INNER JOIN $wpdb->term_taxonomy AS tt ON t.term_id = tt.term_id WHERE t.name IN ('".$term."') AND tt.taxonomy = 'post_tag' ORDER BY t.name ASC" );
    
    if( !empty( $terms ) ) {
        $wpdb->delete( $wpdb->term_taxonomy, array( 'term_taxonomy_id' => $terms->term_taxonomy_id ) );
        $wpdb->delete( $wpdb->terms, array( 'term_id' => $terms->term_id ) );
       }
    }
    
Comments