settings = Plugin::get_settings( 'taxonomies' ); $this->selected_taxonomy = $this->settings['bulk_delete_terms_taxonomy'] ?? ''; add_action( 'init', [ $this, 'init' ], 999 ); add_action( 'adminease_after_field_render', [ $this, 'adminease_after_field_render' ] ); add_filter( 'adminease_settings_fields', [ $this, 'adminease_settings_fields' ] ); if( !current_user_can( 'manage_categories' ) ) { return; } if( !empty( $this->settings['bulk_delete_terms_enabled'] ) ) { add_action( 'admin_enqueue_scripts', [ $this, 'admin_enqueue_scripts' ] ); add_action( 'wp_ajax_adminease_bulk_delete_terms_preview', [ $this, 'ajax_preview_terms' ] ); add_action( 'wp_ajax_adminease_bulk_delete_terms_batch', [ $this, 'ajax_process_batch' ] ); } } /** * Initializes all taxonomies available to the feature. * * @return void */ public function init(): void { $this->init_all_taxonomies(); } /** * Initializes the list of taxonomies offered for bulk deletion. * The free plugin offers Categories and Tags; Pro widens the list through the * filter. The exclusion list is applied after the filter so Pro inherits it. * * @return void */ public function init_all_taxonomies(): void { $taxonomies = apply_filters( 'adminease_bulk_delete_terms_taxonomies_options', Utils::get_taxonomies( [ 'base' ] ) ); foreach( self::EXCLUDED_TAXONOMIES as $excluded_taxonomy ) { unset( $taxonomies[ $excluded_taxonomy ] ); } $this->all_taxonomies = $taxonomies; } /** * Adds custom settings fields for the BulkDeleteTerms feature. * * @param array $fields The existing settings fields to which custom fields will be appended. * * @return array The modified settings fields including the added custom fields. */ public function adminease_settings_fields( array $fields ): array { $link = '' . __( '⚡ Upgrade to Pro', 'adminease' ) . ''; /* translators: %s: link to upgrade to AdminEase Pro */ $bulk_terms_enabled_str = sprintf( __( 'Allow bulk deletion of categories and tags with real-time progress tracking. Need custom taxonomy support? %s', 'adminease' ), $link ); if( Utils::is_pro_plugin_active() ) { $bulk_terms_enabled_str = __( 'Allow bulk deletion of categories, tags, and custom taxonomy terms with real-time progress tracking.', 'adminease' ); } $fields['taxonomies']['fields'][] = [ 'type' => 'switch', 'id' => 'bulk-delete-terms-enabled', 'name' => 'adminease[taxonomies][bulk_delete_terms_enabled]', 'value' => $this->settings['bulk_delete_terms_enabled'] ?? false, 'label_class' => 'pwp-switch', 'input_class' => 'pwp-field-input toggle-field', 'label' => __( 'Enable Bulk Delete Terms', 'adminease' ), 'risk' => 'destructive', 'breaks' => __( 'Adds a tool that can delete many terms for good.', 'adminease' ), 'description' => $bulk_terms_enabled_str, 'field_description' => __( 'Enable to activate the bulk delete feature for taxonomy terms. WARNING: Term deletion is always permanent and cannot be undone!', 'adminease' ), 'child_fields' => [ [ 'type' => 'select', 'id' => 'bulk-delete-terms-taxonomy', 'name' => 'adminease[taxonomies][bulk_delete_terms_taxonomy]', 'value' => $this->selected_taxonomy, 'options' => $this->all_taxonomies, 'label_class' => 'pwp-field-label', 'input_class' => 'pwp-field-input adminease-choices', 'wrapper_class' => 'form-group-child', 'label' => __( 'Select taxonomy', 'adminease' ), 'description' => __( 'Choose which taxonomy to delete terms from.', 'adminease' ), 'attributes' => [ 'data-parent' => 'bulk-delete-terms-enabled', ], ], [ 'type' => 'switch', 'id' => 'bulk-delete-terms-empty-only', 'name' => 'adminease[taxonomies][bulk_delete_terms_empty_only]', 'value' => $this->settings['bulk_delete_terms_empty_only'] ?? false, 'label_class' => 'pwp-switch', 'input_class' => 'pwp-field-input', 'wrapper_class' => 'form-group-child', 'label' => __( 'Empty terms only', 'adminease' ), 'description' => __( 'Only delete terms that have no content assigned to them.', 'adminease' ), 'field_description' => __( 'Recommended for cleaning up unused terms safely.', 'adminease' ), 'attributes' => [ 'data-parent' => 'bulk-delete-terms-enabled', ], ], [ 'type' => 'text', 'id' => 'bulk-delete-terms-name-search', 'name' => 'adminease[taxonomies][bulk_delete_terms_name_search]', 'value' => $this->settings['bulk_delete_terms_name_search'] ?? '', 'label_class' => 'pwp-field-label', 'input_class' => 'pwp-field-input', 'wrapper_class' => 'form-group-child', 'label' => __( 'Name search (optional)', 'adminease' ), 'description' => __( 'Only delete terms whose name or slug contains this text. Leave empty to include all terms.', 'adminease' ), 'attributes' => [ 'data-parent' => 'bulk-delete-terms-enabled', ], ], [ 'type' => 'switch', 'id' => 'bulk-delete-terms-delete-children', 'name' => 'adminease[taxonomies][bulk_delete_terms_delete_children]', 'value' => $this->settings['bulk_delete_terms_delete_children'] ?? false, 'label_class' => 'pwp-switch', 'input_class' => 'pwp-field-input', 'wrapper_class' => 'form-group-child', 'label' => __( 'Delete Child Terms', 'adminease' ), 'description' => __( 'Also delete all child terms of every deleted term. When disabled, WordPress moves children up to the parent of the deleted term.', 'adminease' ), 'field_description' => __( 'Only applies to hierarchical taxonomies such as Categories.', 'adminease' ), 'attributes' => [ 'data-parent' => 'bulk-delete-terms-enabled', ], ], [ 'type' => 'number', 'id' => 'bulk-delete-terms-batch-size', 'name' => 'adminease[taxonomies][bulk_delete_terms_batch_size]', 'value' => $this->settings['bulk_delete_terms_batch_size'] ?? 20, 'label_class' => '', 'input_class' => 'pwp-field-input', 'wrapper_class' => 'form-group-child', 'label' => __( 'Batch Size', 'adminease' ), 'description' => __( 'Number of terms to process per batch. Lower values are safer for slower servers.', 'adminease' ), 'field_description' => __( 'Set between 10 and 100 terms per batch.', 'adminease' ), 'min' => 10, 'max' => 100, 'attributes' => [ 'data-parent' => 'bulk-delete-terms-enabled', ], ], [ 'type' => 'button', 'id' => 'bulk-delete-terms-submit', 'input_class' => 'pwp-btn pwp-btn-primary', 'label' => __( 'Preview', 'adminease' ), 'field_description' => __( 'Click to preview the terms that will be deleted based on selected criteria.', 'adminease' ), 'attributes' => [ 'data-parent' => 'bulk-delete-terms-enabled', 'role' => 'button', ], ], ], ]; return $fields; } /** * Performs operations after a specific field is rendered in the admin interface. * * @param array $field The field data array, which contains attributes such as the field ID. * * @return void */ public function adminease_after_field_render( array $field ): void { if( 'bulk-delete-terms-enabled' !== $field['id'] ) { return; } if( !current_user_can( 'manage_options' ) ) { return; } if( !file_exists( ADMINEASE_DIR . 'partials/bulk-delete-terms.php' ) ) { return; } include ADMINEASE_DIR . 'partials/bulk-delete-terms.php'; } /** * Enqueue JavaScript assets for the bulk delete terms feature. * * @param string $hook The current admin page hook. * * @return void */ public function admin_enqueue_scripts( string $hook ): void { if( 'toplevel_page_adminease' !== $hook ) { return; } wp_enqueue_script( ADMINEASE_NAME . 'BulkDeleteTerms', ADMINEASE_PLUGIN_URL . 'assets/js/AdminEaseBulkDeleteTerms.js', [ 'jquery', ADMINEASE_NAME . 'ProgressBar' ], filemtime( ADMINEASE_DIR . 'assets/js/AdminEaseBulkDeleteTerms.js' ), true ); wp_localize_script( ADMINEASE_NAME . 'BulkDeleteTerms', ADMINEASE_NAME . 'BulkDeleteTermsAjaxObj', [ 'ajaxUrl' => admin_url( 'admin-ajax.php' ), 'security' => wp_create_nonce( 'adminease_bulk_delete_terms_nonce' ), 'batchSize' => absint( $this->settings['bulk_delete_terms_batch_size'] ?? 20 ), 'i18n' => [ 'confirmPermanent' => esc_html__( 'WARNING: You are about to PERMANENTLY delete the selected terms. Term deletion CANNOT be undone. Are you absolutely sure?', 'adminease' ), 'confirmChildren' => esc_html__( 'WARNING: "Delete Child Terms" is enabled, so every child term below the selected terms will be permanently deleted too. Are you absolutely sure?', 'adminease' ), 'processing' => esc_html__( 'Processing...', 'adminease' ), 'complete' => esc_html__( 'Deletion Complete!', 'adminease' ), 'error' => esc_html__( 'An error occurred. Refresh the page and try again.', 'adminease' ), /* translators: %1$d: HTTP status code, %2$s: message returned by the server */ 'httpError' => esc_html__( 'Request failed (HTTP %1$d): %2$s', 'adminease' ), /* translators: %d: HTTP status code returned by the gateway */ 'gatewayError' => esc_html__( 'The server took too long to respond and the request timed out at the gateway (HTTP %d). Lower the batch size and try again.', 'adminease' ), 'networkError' => esc_html__( 'The server could not be reached. Check your connection and try again.', 'adminease' ), 'selectTaxonomy' => esc_html__( 'Please select a taxonomy.', 'adminease' ), 'noTermsFound' => esc_html__( 'No terms found matching the criteria.', 'adminease' ), /* translators: %1$d: number of terms found, %2$s: taxonomy label */ 'foundTerms' => esc_html__( 'Found %1$d terms in %2$s matching criteria', 'adminease' ), 'deletedTerms' => esc_html__( 'Deleted Terms:', 'adminease' ), /* translators: %d: number of terms deleted so far */ 'totalDeleted' => esc_html__( 'Total: %d terms deleted', 'adminease' ), 'startButton' => esc_html__( 'Start Bulk Delete', 'adminease' ), 'stopButton' => esc_html__( 'Stop', 'adminease' ), 'stopping' => esc_html__( 'Stopping...', 'adminease' ), 'stopped' => esc_html__( 'Deletion stopped.', 'adminease' ), 'term' => esc_html__( 'Term', 'adminease' ), 'child' => esc_html__( 'child', 'adminease' ), 'errorsTitle' => esc_html__( 'Errors:', 'adminease' ), ], ] ); } /** * Builds the shared get_terms() arguments used by both the preview and the * batch endpoint, so the two can never drift apart. * * @param string $taxonomy The taxonomy to query. * @param string $name_search Optional name/slug search string. * * @return array The query arguments. */ private function get_query_args( string $taxonomy, string $name_search ): array { $query_args = [ 'taxonomy' => $taxonomy, 'hide_empty' => false, 'exclude' => $this->get_protected_term_ids( $taxonomy ), // phpcs:ignore WordPressVIPMinimum.Performance.WPQueryParams.PostNotIn_exclude ]; if( !empty( $name_search ) ) { $query_args['search'] = $name_search; } return apply_filters( 'adminease_bulk_delete_terms_query_args', $query_args, $taxonomy ); } /** * Returns term IDs that must never be deleted. * * A taxonomy's default term cannot be removed: wp_delete_term() rejects it with * a 'default_term' error. Leaving it in the result set would make every batch * delete nothing while the remaining count stayed positive, so the front-end * would loop forever. Excluding it up front keeps the counts honest. * * @param string $taxonomy The taxonomy being processed. * * @return array List of protected term IDs. */ private function get_protected_term_ids( string $taxonomy ): array { $default_term_id = (int) get_option( 'default_' . $taxonomy, 0 ); if( empty( $default_term_id ) ) { $default_term_id = (int) get_option( 'default_term_' . $taxonomy, 0 ); } $protected_term_ids = empty( $default_term_id ) ? [] : [ $default_term_id ]; return apply_filters( 'adminease_bulk_delete_terms_protected_ids', $protected_term_ids, $taxonomy ); } /** * Restricts a term query to terms with no content assigned. * get_terms() has no native argument for "count is zero", so the clause is added * here. The condition is a fixed literal with no user input, so no preparation * is required. Applied through terms_clauses (rather than filtering results in * PHP) so that totals and batch sizes stay accurate. * * @param array $clauses The term query clauses. * * @return array The modified clauses. */ public function terms_clauses_empty_only( array $clauses ): array { $clauses['where'] .= ' AND tt.count = 0'; return $clauses; } /** * Runs get_terms() with the empty-only clause applied when requested. * The filter is added and removed around the single call so it can never leak * into unrelated term queries. * * @param array $query_args The get_terms() arguments. * @param bool $empty_only Whether to restrict the query to empty terms. * * @return array|int|WP_Error The get_terms() result. */ private function query_terms( array $query_args, bool $empty_only ) { if( $empty_only ) { add_filter( 'terms_clauses', [ $this, 'terms_clauses_empty_only' ] ); } $terms = get_terms( $query_args ); if( $empty_only ) { remove_filter( 'terms_clauses', [ $this, 'terms_clauses_empty_only' ] ); } return $terms; } /** * Validates the shared request parameters for both AJAX endpoints. * Sends a JSON error and stops execution when validation fails. * * @return array The validated request parameters. */ private function validate_request(): array { if( !isset( $_POST['security'] ) || !wp_verify_nonce( sanitize_key( wp_unslash( $_POST['security'] ) ), 'adminease_bulk_delete_terms_nonce' ) ) { wp_send_json_error( new WP_Error( 'security_error', esc_html__( 'Security check failed. Refresh the page and try again.', 'adminease' ) ), 403 ); } if( !current_user_can( 'manage_options' ) ) { wp_send_json_error( new WP_Error( 'permissions', esc_html__( 'You do not have sufficient permissions to perform this action', 'adminease' ) ) ); } $taxonomy = isset( $_POST['taxonomy'] ) ? sanitize_key( wp_unslash( $_POST['taxonomy'] ) ) : ''; if( empty( $taxonomy ) || !array_key_exists( $taxonomy, $this->all_taxonomies ) ) { wp_send_json_error( [ 'message' => esc_html__( 'Please select a valid taxonomy.', 'adminease' ) ] ); } if( !taxonomy_exists( $taxonomy ) ) { wp_send_json_error( [ 'message' => esc_html__( 'Invalid taxonomy selected.', 'adminease' ) ] ); } return [ 'taxonomy' => $taxonomy, 'name_search' => isset( $_POST['name_search'] ) ? sanitize_text_field( wp_unslash( $_POST['name_search'] ) ) : '', 'empty_only' => isset( $_POST['empty_only'] ) && 'true' === sanitize_key( wp_unslash( $_POST['empty_only'] ) ), ]; } /** * AJAX handler for previewing terms that match the criteria. * * @return void */ public function ajax_preview_terms(): void { $request = $this->validate_request(); $query_args = $this->get_query_args( $request['taxonomy'], $request['name_search'] ); $query_args['fields'] = 'count'; $total = $this->query_terms( $query_args, $request['empty_only'] ); if( is_wp_error( $total ) ) { wp_send_json_error( [ 'message' => $total->get_error_message() ] ); } $taxonomy_object = get_taxonomy( $request['taxonomy'] ); wp_send_json_success( [ 'total' => (int) $total, 'taxonomy_label' => $taxonomy_object->label, 'hierarchical' => is_taxonomy_hierarchical( $request['taxonomy'] ), ] ); } /** * AJAX handler for processing a batch of term deletions. * * @return void */ public function ajax_process_batch(): void { $request = $this->validate_request(); $taxonomy = $request['taxonomy']; $empty_only = $request['empty_only']; // phpcs:disable WordPress.Security.NonceVerification.Missing -- Nonce is verified in validate_request() above. $delete_children = isset( $_POST['delete_children'] ) && 'true' === sanitize_key( wp_unslash( $_POST['delete_children'] ) ) && is_taxonomy_hierarchical( $taxonomy ); $page = isset( $_POST['page'] ) ? absint( $_POST['page'] ) : 1; $batch_size = absint( !empty( $_POST['batch_size'] ) ? sanitize_text_field( wp_unslash( $_POST['batch_size'] ) ) : ( $this->settings['bulk_delete_terms_batch_size'] ?? 20 ) ); // phpcs:enable WordPress.Security.NonceVerification.Missing if( empty( $batch_size ) ) { $batch_size = 20; } $query_args = $this->get_query_args( $taxonomy, $request['name_search'] ); $query_args['number'] = $batch_size; $query_args['offset'] = 0; $query_args['fields'] = 'all'; $terms = $this->query_terms( $query_args, $empty_only ); if( is_wp_error( $terms ) ) { wp_send_json_error( [ 'message' => $terms->get_error_message() ] ); } $deleted = []; $errors = []; $deleted_ids = []; $batch_started = microtime( true ); $time_budget = (float) apply_filters( 'adminease_bulk_delete_terms_time_budget', self::BATCH_TIME_BUDGET ); do_action( 'adminease_bulk_delete_terms_batch_start', $terms, $page, $taxonomy ); foreach( $terms as $term ) { if( microtime( true ) - $batch_started >= $time_budget ) { break; } if( in_array( (int) $term->term_id, $deleted_ids, true ) ) { continue; } if( $delete_children ) { foreach( $this->delete_term_children( (int) $term->term_id, $taxonomy, $errors ) as $deleted_child ) { $deleted[] = $deleted_child; $deleted_ids[] = $deleted_child['id']; } } $result = wp_delete_term( (int) $term->term_id, $taxonomy ); if( is_wp_error( $result ) ) { $errors[] = [ 'id' => (int) $term->term_id, 'name' => $term->name, 'error' => $result->get_error_message(), ]; continue; } if( false === $result ) { $errors[] = [ 'id' => (int) $term->term_id, 'name' => $term->name, 'error' => esc_html__( 'Term could not be deleted.', 'adminease' ), ]; continue; } $deleted[] = [ 'id' => (int) $term->term_id, 'name' => $term->name, 'is_child' => false, ]; $deleted_ids[] = (int) $term->term_id; do_action( 'adminease_bulk_delete_term', (int) $term->term_id, $taxonomy ); } $remaining_args = $this->get_query_args( $taxonomy, $request['name_search'] ); $remaining_args['fields'] = 'count'; $total_remaining = $this->query_terms( $remaining_args, $empty_only ); $total_remaining = is_wp_error( $total_remaining ) ? 0 : (int) $total_remaining; $stalled = false; if( empty( $deleted ) && $total_remaining > 0 ) { $stalled = true; $total_remaining = 0; } do_action( 'adminease_bulk_delete_terms_batch_complete', $deleted, $errors, $page, $taxonomy ); wp_send_json_success( [ 'deleted' => $deleted, 'errors' => $errors, 'processed' => count( $deleted ), 'total_remaining' => $total_remaining, 'current_page' => $page, 'stalled' => $stalled, 'stalled_message' => $stalled ? esc_html__( 'Stopped: the remaining terms could not be deleted. See the errors below.', 'adminease' ) : '', ] ); } /** * Recursively deletes every child term below the given term. * * @param int $term_id The parent term ID. * @param string $taxonomy The taxonomy being processed. * @param array $errors Collected errors, passed by reference. * * @return array The deleted child terms. */ private function delete_term_children( int $term_id, string $taxonomy, array &$errors ): array { $children = get_term_children( $term_id, $taxonomy ); if( is_wp_error( $children ) || empty( $children ) ) { return []; } $deleted = []; foreach( $children as $child_id ) { $child = get_term( (int) $child_id, $taxonomy ); if( is_wp_error( $child ) || null === $child ) { continue; } $result = wp_delete_term( (int) $child_id, $taxonomy ); if( is_wp_error( $result ) || false === $result ) { $errors[] = [ 'id' => (int) $child_id, 'name' => $child->name, 'error' => is_wp_error( $result ) ? $result->get_error_message() : esc_html__( 'Term could not be deleted.', 'adminease' ), ]; continue; } $deleted[] = [ 'id' => (int) $child_id, 'name' => $child->name, 'is_child' => true, ]; do_action( 'adminease_bulk_delete_term', (int) $child_id, $taxonomy ); } return $deleted; } }