Skip to content

Commit 50e6e08

Browse files
Copilotswissspidy
andcommitted
Refactor prune() to use direct DB query instead of get_terms() for better performance
Co-authored-by: swissspidy <841956+swissspidy@users.noreply.github.com>
1 parent be42053 commit 50e6e08

1 file changed

Lines changed: 13 additions & 25 deletions

File tree

src/Term_Command.php

Lines changed: 13 additions & 25 deletions
Original file line numberDiff line numberDiff line change
@@ -722,55 +722,43 @@ public function recount( $args ) {
722722
* Success: Pruned 1 of 5 terms.
723723
*/
724724
public function prune( $args, $assoc_args ) {
725+
global $wpdb;
726+
725727
$dry_run = (bool) Utils\get_flag_value( $assoc_args, 'dry-run', false );
726728

727729
foreach ( $args as $taxonomy ) {
728730
if ( ! taxonomy_exists( $taxonomy ) ) {
729731
WP_CLI::error( "Taxonomy {$taxonomy} doesn't exist." );
730732
}
731733

732-
$terms = get_terms(
733-
[
734-
'taxonomy' => $taxonomy,
735-
'hide_empty' => false,
736-
]
734+
$term_ids_to_prune = $wpdb->get_col(
735+
$wpdb->prepare(
736+
"SELECT term_id FROM {$wpdb->term_taxonomy} WHERE taxonomy = %s AND count <= 1",
737+
$taxonomy
738+
)
737739
);
738740

739-
// This should never happen because of the taxonomy_exists check above.
740-
if ( is_wp_error( $terms ) ) {
741-
WP_CLI::warning( "Could not retrieve terms for taxonomy {$taxonomy}." );
742-
continue;
743-
}
744-
745-
/**
746-
* @var \WP_Term[] $terms
747-
*/
748-
749-
$total = count( $terms );
741+
$total = count( $term_ids_to_prune );
750742
$successes = 0;
751743
$errors = 0;
752744

753-
foreach ( $terms as $term ) {
754-
if ( $term->count > 1 ) {
755-
continue;
756-
}
757-
745+
foreach ( $term_ids_to_prune as $term_id ) {
758746
if ( $dry_run ) {
759-
WP_CLI::log( "Would delete {$taxonomy} {$term->term_id}." );
747+
WP_CLI::log( "Would delete {$taxonomy} {$term_id}." );
760748
++$successes;
761749
continue;
762750
}
763751

764-
$result = wp_delete_term( $term->term_id, $taxonomy );
752+
$result = wp_delete_term( $term_id, $taxonomy );
765753

766754
if ( is_wp_error( $result ) ) {
767755
WP_CLI::warning( $result );
768756
++$errors;
769757
} elseif ( $result ) {
770-
WP_CLI::log( "Deleted {$taxonomy} {$term->term_id}." );
758+
WP_CLI::log( "Deleted {$taxonomy} {$term_id}." );
771759
++$successes;
772760
} else {
773-
WP_CLI::warning( "Failed to delete {$taxonomy} {$term->term_id}." );
761+
WP_CLI::warning( "Term {$term_id} in taxonomy {$taxonomy} doesn't exist." );
774762
++$errors;
775763
}
776764
}

0 commit comments

Comments
 (0)