Cancellare un'Intera Tassonomia dal Database

Cancellare un'Intera Tassonomia dal Database

Per assolvere ad un'operazione come questa, non c'è nessuna funzione in WordPress pensata allo scopo. D'altronde, cancellare tutti i dati associati ad una tassonomia non è un'operazione comune, o al meno non un'azione di routine. Io, per esempio, mi sono trovato dinanzi il problema mentre scrivevo lo script uninstall.php per SiteTree Pro 4.0 — un file caricato quando non sono neanche disponibili tutte le funzioni di WordPress, oltretutto. Ma pur considerando un contesto più generico, la soluzione più agevole che può essere adottata è quella di usare tre query personalizzate:

1global $wpdb;
2
3$taxonomy_name = 'the_taxonomy_to_delete';
4
5# Deletes all the terms associated to the taxonomy.
6#
7# The inner query collects from the 'term_taxonomy' 
8# table all the ids of the terms to delete.
9$wpdb->query( 
10  "DELETE FROM {$wpdb->terms} AS t 
11   WHERE t.term_id IN (
12    SELECT tt.term_id FROM {$wpdb->term_taxonomy} AS tt
13    WHERE tt.taxonomy = '{$taxonomy_name}'
14   )"
15);
16
17# Deletes the information used by WordPress 
18# to link each post to their terms.
19#
20# Here too, a nested query is needed, 
21# and the 'term_taxonomy' table is yet again 
22# the source of the data passed to the outer query.
23# But in this case to be collected by 
24# the inner query are the ids of 
25# the Relationships to delete.
26$wpdb->query( 
27  "DELETE FROM {$wpdb->term_relationships} AS tr 
28   WHERE tr.term_taxonomy_id IN (
29    SELECT tt.term_taxonomy_id FROM {$wpdb->term_taxonomy} AS tt
30    WHERE tt.taxonomy = '{$taxonomy_name}'
31   )"
32);
33
34# Deletes the base information about the taxonomy. 
35$wpdb->query( 
36  "DELETE FROM {$wpdb->term_taxonomy} 
37   WHERE taxonomy = '{$taxonomy_name}'"
38);

Il database deve essere interrogato in tre momenti distinti non solo perché tre sono le tabelle da cui cancellare i dati, ma soprattutto perché due di queste, terms e term_relationships, dipendono dalla terza, term_taxonomy.

TOP