settings = Plugin::get_settings( 'taxonomies' ); $this->source_taxonomy = $this->settings['taxonomy_switcher_source'] ?? ''; $this->target_taxonomy = $this->settings['taxonomy_switcher_target'] ?? ''; 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['taxonomy_switcher_enabled'] ) ) { add_action( 'admin_enqueue_scripts', [ $this, 'admin_enqueue_scripts' ] ); add_action( 'wp_ajax_adminease_taxonomy_switch_preview', [ $this, 'ajax_preview_terms' ] ); add_action( 'wp_ajax_adminease_taxonomy_switch_batch', [ $this, 'ajax_process_batch' ] ); add_action( 'wp_ajax_adminease_taxonomy_switch_validate', [ $this, 'ajax_validate_taxonomies' ] ); } } /** * Initializes all taxonomies. * This method sets up necessary data or configurations related to all taxonomies. * * @return void */ public function init() { $this->init_all_taxonomies(); } /** * Initializes all public taxonomies for use within the system. * Filters out built-in taxonomies like post_format and nav_menu. * * @return void */ public function init_all_taxonomies() { $taxonomies = get_taxonomies( [ 'public' => true, 'show_ui' => true, ], 'objects' ); $excluded = [ 'post_format', 'nav_menu', 'link_category', 'post_status_ae' ]; foreach( $taxonomies as $taxonomy ) { if( !in_array( $taxonomy->name, $excluded ) ) { $this->all_taxonomies[ $taxonomy->name ] = $taxonomy->label; } } $this->all_taxonomies = apply_filters( 'adminease_taxonomy_switcher_taxonomies_options', $this->all_taxonomies ); } /** * Adds custom settings fields for the TaxonomySwitcher 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 { $fields['taxonomies']['fields'][] = [ 'type' => 'switch', 'id' => 'taxonomy-switcher-enabled', 'name' => 'adminease[taxonomies][taxonomy_switcher_enabled]', 'value' => $this->settings['taxonomy_switcher_enabled'] ?? false, 'label_class' => 'pwp-switch', 'input_class' => 'pwp-field-input toggle-field', 'label' => __( 'Enable Taxonomy Switcher', 'adminease' ), 'description' => __( 'Allow switching terms from one taxonomy to another with real-time progress tracking. Useful for migrating categories to tags or custom taxonomies.', 'adminease' ), 'field_description' => __( 'Enable to activate the taxonomy switcher feature.', 'adminease' ), 'child_fields' => [ [ 'type' => 'number', 'id' => 'taxonomy-switcher-batch-size', 'name' => 'adminease[taxonomies][taxonomy_switcher_batch_size]', 'value' => $this->settings['taxonomy_switcher_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' => 'taxonomy-switcher-enabled', ], ], [ 'type' => 'select', 'id' => 'taxonomy-switcher-source', 'name' => 'adminease[taxonomies][taxonomy_switcher_source]', 'value' => $this->source_taxonomy, 'options' => $this->all_taxonomies, 'label_class' => 'pwp-field-label', 'input_class' => 'pwp-field-input adminease-choices', 'wrapper_class' => 'form-group-child', 'label' => __( 'Source Taxonomy', 'adminease' ), 'description' => __( 'Select the taxonomy to move terms FROM.', 'adminease' ), 'attributes' => [ 'data-parent' => 'taxonomy-switcher-enabled', ], ], [ 'type' => 'select', 'id' => 'taxonomy-switcher-target', 'name' => 'adminease[taxonomies][taxonomy_switcher_target]', 'value' => $this->target_taxonomy, 'options' => $this->all_taxonomies, 'label_class' => 'pwp-field-label', 'input_class' => 'pwp-field-input adminease-choices', 'wrapper_class' => 'form-group-child', 'label' => __( 'Target Taxonomy', 'adminease' ), 'description' => __( 'Select the taxonomy to move terms TO.', 'adminease' ), 'attributes' => [ 'data-parent' => 'taxonomy-switcher-enabled', ], ], [ 'type' => 'switch', 'id' => 'taxonomy-switcher-delete-source', 'name' => 'adminease[taxonomies][taxonomy_switcher_delete_source]', 'value' => $this->settings['taxonomy_switcher_delete_source'] ?? false, 'label_class' => 'pwp-switch', 'input_class' => 'pwp-field-input', 'wrapper_class' => 'form-group-child', 'label' => __( 'Delete Source Terms', 'adminease' ), 'description' => __( 'After switching, delete the original terms from the source taxonomy. WARNING: This action cannot be undone!', 'adminease' ), 'attributes' => [ 'data-parent' => 'taxonomy-switcher-enabled', ], ], [ 'type' => 'switch', 'id' => 'taxonomy-switcher-merge-duplicates', 'name' => 'adminease[taxonomies][taxonomy_switcher_merge_duplicates]', 'value' => $this->settings['taxonomy_switcher_merge_duplicates'] ?? true, 'label_class' => 'pwp-switch', 'input_class' => 'pwp-field-input', 'wrapper_class' => 'form-group-child', 'label' => __( 'Merge Duplicate Terms', 'adminease' ), 'description' => __( 'If a term with the same name exists in the target taxonomy, merge them instead of creating duplicates.', 'adminease' ), 'attributes' => [ 'data-parent' => 'taxonomy-switcher-enabled', ], ], [ 'type' => 'button', 'id' => 'taxonomy-switcher-submit', 'input_class' => 'pwp-btn pwp-btn-primary', 'label' => __( 'Preview', 'adminease' ), 'field_description' => __( 'Click to preview the terms that will be switched.', 'adminease' ), 'attributes' => [ 'data-parent' => 'taxonomy-switcher-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( 'taxonomy-switcher-enabled' !== $field['id'] ) { return; } if( !current_user_can( 'manage_options' ) ) { return; } if( !file_exists( ADMINEASE_DIR . 'partials/taxonomy-switcher.php' ) ) { return; } include ADMINEASE_DIR . 'partials/taxonomy-switcher.php'; } /** * Enqueue JavaScript and CSS assets for the taxonomy switcher feature. * * @param $hook * * @return void */ public function admin_enqueue_scripts( $hook ): void { if( 'toplevel_page_adminease' !== $hook ) { return; } wp_enqueue_script( ADMINEASE_NAME . 'TaxonomySwitcher', ADMINEASE_PLUGIN_URL . 'assets/js/AdminEaseTaxonomySwitcher.js', [ 'jquery', ADMINEASE_NAME . 'ProgressBar' ], filemtime( ADMINEASE_DIR . 'assets/js/AdminEaseTaxonomySwitcher.js' ), true ); wp_localize_script( ADMINEASE_NAME . 'TaxonomySwitcher', ADMINEASE_NAME . 'TaxonomySwitcherAjaxObj', [ 'ajaxUrl' => admin_url( 'admin-ajax.php' ), 'security' => wp_create_nonce( 'adminease_taxonomy_switch_nonce' ), 'batchSize' => absint( $this->settings['taxonomy_switcher_batch_size'] ?? 20 ), 'i18n' => [ 'confirmTitle' => esc_html__( 'Confirm Taxonomy Switch', 'adminease' ), 'confirmMessage' => esc_html__( 'Are you sure you want to switch the selected terms? This action may affect your content.', 'adminease' ), 'confirmDelete' => esc_html__( 'WARNING: You have chosen to delete source terms. This action CANNOT be undone. Are you absolutely sure?', 'adminease' ), 'processing' => esc_html__( 'Processing...', 'adminease' ), 'complete' => esc_html__( 'Switch 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' ), 'noTermsFound' => esc_html__( 'No terms found in the source taxonomy.', 'adminease' ), 'sameTaxonomy' => esc_html__( 'Source and target taxonomies cannot be the same.', 'adminease' ), 'selectBoth' => esc_html__( 'Please select both source and target taxonomies.', 'adminease' ), /* translators: 1: number of terms found, 2: source taxonomy label, 3: target taxonomy label */ 'foundTerms' => esc_html__( 'Found %1$d terms in %2$s to move to %3$s', 'adminease' ), 'switchedTerms' => esc_html__( 'Switched Terms:', 'adminease' ), /* translators: %d: number of terms switched so far */ 'totalSwitched' => esc_html__( 'Total: %d terms switched', 'adminease' ), 'startButton' => esc_html__( 'Start Taxonomy Switch', 'adminease' ), 'incompatiblePostTypes' => esc_html__( 'Warning: Source and target taxonomies may not share the same post types. This could cause issues.', 'adminease' ), /* translators: 1: ID of the original term, 2: ID of the term it became */ 'switchedMeta' => esc_html__( 'ID: %1$d to %2$d', 'adminease' ), /* translators: %d: ID of the term that could not be switched */ 'errorMeta' => esc_html__( 'ID: %d', 'adminease' ), 'noProgress' => esc_html__( 'Stopped: no further terms could be switched. See the errors below.', 'adminease' ), 'tooManyErrors' => esc_html__( 'Stopped: too many terms failed to switch. See the errors below.', 'adminease' ), ], ] ); } /** * AJAX handler for validating taxonomy compatibility. * * @return void */ public function ajax_validate_taxonomies(): void { if( !isset( $_POST['security'] ) || !wp_verify_nonce( sanitize_key( wp_unslash( $_POST['security'] ) ), 'adminease_taxonomy_switch_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_categories' ) ) { wp_send_json_error( new WP_Error( 'permissions', esc_html__( 'You do not have sufficient permissions to perform this action', 'adminease' ) ) ); } $source_tax = isset( $_POST['source_taxonomy'] ) ? sanitize_key( wp_unslash( $_POST['source_taxonomy'] ) ) : ''; $target_tax = isset( $_POST['target_taxonomy'] ) ? sanitize_key( wp_unslash( $_POST['target_taxonomy'] ) ) : ''; if( empty( $source_tax ) || empty( $target_tax ) ) { wp_send_json_error( [ 'message' => esc_html__( 'Please select both source and target taxonomies.', 'adminease' ) ] ); } if( $source_tax === $target_tax ) { wp_send_json_error( [ 'message' => esc_html__( 'Source and target taxonomies must be different.', 'adminease' ) ] ); } $source_taxonomy = get_taxonomy( $source_tax ); $target_taxonomy = get_taxonomy( $target_tax ); if( !$source_taxonomy || !$target_taxonomy ) { wp_send_json_error( [ 'message' => esc_html__( 'Invalid taxonomy selected.', 'adminease' ) ] ); } $shared_post_types = array_intersect( $source_taxonomy->object_type, $target_taxonomy->object_type ); wp_send_json_success( [ 'compatible' => !empty( $shared_post_types ), 'shared_post_types' => $shared_post_types, 'source_post_types' => $source_taxonomy->object_type, 'target_post_types' => $target_taxonomy->object_type, ] ); } /** * AJAX handler for previewing terms that will be switched. * * @return void */ public function ajax_preview_terms(): void { if( !isset( $_POST['security'] ) || !wp_verify_nonce( sanitize_key( wp_unslash( $_POST['security'] ) ), 'adminease_taxonomy_switch_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_categories' ) ) { wp_send_json_error( new WP_Error( 'permissions', esc_html__( 'You do not have sufficient permissions to perform this action', 'adminease' ) ) ); } $source_tax = isset( $_POST['source_taxonomy'] ) ? sanitize_key( wp_unslash( $_POST['source_taxonomy'] ) ) : ''; $target_tax = isset( $_POST['target_taxonomy'] ) ? sanitize_key( wp_unslash( $_POST['target_taxonomy'] ) ) : ''; if( empty( $source_tax ) || empty( $target_tax ) ) { wp_send_json_error( [ 'message' => esc_html__( 'Please select both source and target taxonomies.', 'adminease' ) ] ); } if( $source_tax === $target_tax ) { wp_send_json_error( [ 'message' => esc_html__( 'Source and target taxonomies cannot be the same.', 'adminease' ) ] ); } if( !taxonomy_exists( $source_tax ) || !taxonomy_exists( $target_tax ) ) { wp_send_json_error( [ 'message' => esc_html__( 'Invalid taxonomy selected.', 'adminease' ) ] ); } $terms = get_terms( [ 'taxonomy' => $source_tax, 'hide_empty' => false, 'fields' => 'ids', ] ); if( is_wp_error( $terms ) ) { wp_send_json_error( [ 'message' => $terms->get_error_message() ] ); } $source_taxonomy = get_taxonomy( $source_tax ); $target_taxonomy = get_taxonomy( $target_tax ); $shared_post_types = array_intersect( $source_taxonomy->object_type, $target_taxonomy->object_type ); wp_send_json_success( [ 'total' => count( $terms ), 'source_label' => $source_taxonomy->label, 'target_label' => $target_taxonomy->label, 'compatible' => !empty( $shared_post_types ), 'shared_post_types' => $shared_post_types, ] ); } /** * AJAX handler for processing a batch of term switches. * * @return void */ public function ajax_process_batch(): void { if( !isset( $_POST['security'] ) || !wp_verify_nonce( sanitize_key( wp_unslash( $_POST['security'] ) ), 'adminease_taxonomy_switch_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_categories' ) ) { wp_send_json_error( new WP_Error( 'permissions', esc_html__( 'You do not have sufficient permissions to perform this action', 'adminease' ) ) ); } $source_tax = isset( $_POST['source_taxonomy'] ) ? sanitize_key( wp_unslash( $_POST['source_taxonomy'] ) ) : ''; $target_tax = isset( $_POST['target_taxonomy'] ) ? sanitize_key( wp_unslash( $_POST['target_taxonomy'] ) ) : ''; $delete_source = isset( $_POST['delete_source'] ) && $_POST['delete_source'] === 'true'; $merge_duplicates = isset( $_POST['merge_duplicates'] ) && $_POST['merge_duplicates'] === 'true'; $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['taxonomy_switcher_batch_size'] ?? 20 ) ); if( empty( $source_tax ) || empty( $target_tax ) ) { wp_send_json_error( [ 'message' => esc_html__( 'Please select both source and target taxonomies.', 'adminease' ) ] ); } if( $source_tax === $target_tax ) { wp_send_json_error( [ 'message' => esc_html__( 'Source and target taxonomies cannot be the same.', 'adminease' ) ] ); } $exclude = isset( $_POST['exclude'] ) && is_array( $_POST['exclude'] ) ? array_map( 'absint', $_POST['exclude'] ) : []; $terms = get_terms( [ 'taxonomy' => $source_tax, 'hide_empty' => false, 'number' => $batch_size, 'offset' => $delete_source ? 0 : ( ( $page - 1 ) * $batch_size ), 'exclude' => $exclude, // phpcs:ignore WordPressVIPMinimum.Performance.WPQueryParams.PostNotIn_exclude ] ); if( is_wp_error( $terms ) ) { wp_send_json_error( [ 'message' => $terms->get_error_message() ] ); } $switched = []; $errors = []; do_action( 'adminease_taxonomy_switch_batch_start', $terms, $page, $source_tax, $target_tax ); foreach( $terms as $term ) { $result = $this->switch_term( $term, $source_tax, $target_tax, $merge_duplicates, $delete_source ); if( is_wp_error( $result ) ) { $errors[] = [ 'term_id' => $term->term_id, 'name' => $term->name, 'error' => $result->get_error_message(), ]; } else { $switched[] = [ 'term_id' => $term->term_id, 'name' => $term->name, 'new_term_id' => $result, ]; do_action( 'adminease_taxonomy_switch_term', $term->term_id, $result, $source_tax, $target_tax ); } } if( $delete_source ) { $remaining_terms = get_terms( [ 'taxonomy' => $source_tax, 'hide_empty' => false, 'fields' => 'count', 'exclude' => $exclude, // phpcs:ignore WordPressVIPMinimum.Performance.WPQueryParams.PostNotIn_exclude ] ); $remaining_count = is_wp_error( $remaining_terms ) ? 0 : $remaining_terms; } else { $all_terms_count = wp_count_terms( [ 'taxonomy' => $source_tax, 'hide_empty' => false, ] ); $processed_so_far = $page * $batch_size; $remaining_count = max( 0, (int) $all_terms_count - $processed_so_far ); } do_action( 'adminease_taxonomy_switch_batch_complete', $switched, $errors, $page ); $stalled = false; if( empty( $terms ) && $remaining_count > 0 ) { $stalled = true; $remaining_count = 0; } wp_send_json_success( [ 'switched' => $switched, 'errors' => $errors, 'processed' => count( $switched ), 'total_remaining' => $remaining_count, 'current_page' => $page, 'stalled' => $stalled, 'stalled_message' => $stalled ? esc_html__( 'Stopped: the remaining terms could not be reached. See the errors below.', 'adminease' ) : '', ] ); } /** * Switch a term from source taxonomy to target taxonomy. * * @param object $term The term object to switch. * @param string $source_tax Source taxonomy. * @param string $target_tax Target taxonomy. * @param bool $merge_duplicates Whether to merge with existing terms. * @param bool $delete_source Whether to delete the source term after switching. * * @return int|WP_Error The new term ID on success, WP_Error on failure. */ private function switch_term( $term, string $source_tax, string $target_tax, bool $merge_duplicates, bool $delete_source ) { $existing_term = get_term_by( 'name', $term->name, $target_tax ); if( $existing_term ) { if( $merge_duplicates ) { $new_term_id = $existing_term->term_id; } else { return new WP_Error( 'term_exists', sprintf( /* translators: %s: term name */ __( 'Term "%s" already exists in target taxonomy. Enable "Merge Duplicate Terms" to merge them.', 'adminease' ), $term->name ) ); } } else { $new_term = wp_insert_term( $term->name, $target_tax, [ 'description' => $term->description, 'slug' => $term->slug, 'parent' => 0, ] ); if( is_wp_error( $new_term ) ) { return $new_term; } $new_term_id = $new_term['term_id']; } $objects = get_objects_in_term( $term->term_id, $source_tax ); if( !is_wp_error( $objects ) && !empty( $objects ) ) { $source_taxonomy = get_taxonomy( $source_tax ); $target_taxonomy = get_taxonomy( $target_tax ); $shared_post_types = array_intersect( $source_taxonomy->object_type, $target_taxonomy->object_type ); foreach( $objects as $object_id ) { $post_type = get_post_type( $object_id ); if( in_array( $post_type, $shared_post_types, true ) || in_array( $post_type, $target_taxonomy->object_type, true ) ) { wp_set_object_terms( $object_id, (int) $new_term_id, $target_tax, true ); if( $delete_source ) { wp_remove_object_terms( $object_id, (int) $term->term_id, $source_tax ); } } } } if( $delete_source ) { $deleted = wp_delete_term( $term->term_id, $source_tax ); if( is_wp_error( $deleted ) ) { return $deleted; } if( !$deleted ) { return new WP_Error( 'delete_failed', __( 'Could not delete source term.', 'adminease' ) ); } } return $new_term_id; } }