settings = Plugin::get_settings( 'taxonomies' ); add_action( 'init', [ $this, 'init' ] ); add_filter( 'adminease_settings_fields', [ $this, 'adminease_settings_fields' ] ); if( !current_user_can( 'edit_posts' ) ) { return; } if( empty( $this->settings['taxonomy_meta_box'] ) ) { return; } add_action( 'admin_enqueue_scripts', [ $this, 'admin_enqueue_scripts' ] ); add_action( 'save_post', [ $this, 'save_taxonomy_terms' ], 10, 2 ); add_action( 'wp_ajax_adminease_load_taxonomy_terms', [ $this, 'ajax_load_taxonomy_terms' ] ); add_action( 'wp_ajax_adminease_search_taxonomy_terms', [ $this, 'ajax_search_taxonomy_terms' ] ); add_action( 'wp_ajax_adminease_create_taxonomy_term', [ $this, 'ajax_create_taxonomy_term' ] ); add_action( 'wp_ajax_adminease_get_term_names', [ $this, 'ajax_get_term_names' ] ); } /** * Initializes the taxonomies to be used within the plugin. * Allows filtering to customize the list of registered taxonomies. * * @return void Sets the class property with the filtered list of taxonomies. */ public function init(): void { $this->taxonomies = apply_filters( 'adminease_taxonomy_meta_box_taxonomies', Utils::get_taxonomies( [ 'base_hierarchical' ] ) ); if( !empty( $this->settings['taxonomy_meta_box'] ) ) { add_action( 'add_meta_boxes', [ $this, 'replace_taxonomy_meta_boxes' ], 999 ); } } /** * Modifies and extends the settings fields array for the plugin. * This method adds a field to enable or disable lazy loading for taxonomy terms, * improving performance on post edit screens with a large number of terms. * * @param array $fields The existing settings fields array to be modified. * * @return array The updated settings fields array with the added taxonomy terms lazy loading field. */ public function adminease_settings_fields( array $fields ): array { $fields['taxonomies']['fields'][] = [ 'type' => 'switch', 'id' => 'taxonomy-meta-box', 'name' => 'adminease[taxonomies][taxonomy_meta_box]', 'value' => $this->settings['taxonomy_meta_box'] ?? false, 'label_class' => 'pwp-switch', 'input_class' => 'pwp-field-input toggle-field', 'label' => __( 'Improved Taxonomy Meta Box', 'adminease' ), 'description' => __( 'Improve performance on the post edit screen by loading taxonomy terms (like categories or tags) dynamically via AJAX. This is especially useful when you have a large number of terms, as it prevents WordPress from loading them all at once, reducing page load time and memory usage. Enable this option to activate a searchable, paginated dropdown that loads terms on demand.', 'adminease' ), 'field_description' => __( 'Will work when Gutenberg is disabled.', 'adminease' ), ]; return $fields; } /** * Enqueues scripts and styles required for the taxonomy meta box on applicable admin pages. * This method conditionally enqueues necessary styles and scripts only for * post edit and new post pages where enabled taxonomies exist for the current post type. * * @param string $hook The admin page hook suffix, e.g., 'post.php' or 'post-new.php'. * * @return void */ public function admin_enqueue_scripts( string $hook ): void { if( !in_array( $hook, [ 'post.php', 'post-new.php' ] ) ) { return; } $current_screen = get_current_screen(); if( !$current_screen ) { return; } $post_type = $current_screen->post_type; $post_type_taxonomies = get_object_taxonomies( $post_type ); $has_enabled_taxonomy = false; foreach( $this->taxonomies as $taxonomy_key => $taxonomy ) { if( in_array( $taxonomy_key, $post_type_taxonomies ) ) { $has_enabled_taxonomy = true; break; } } if( !$has_enabled_taxonomy ) { return; } wp_enqueue_style( ADMINEASE_NAME . 'TaxonomyMetaBox', ADMINEASE_PLUGIN_URL . 'assets/css/AdminEaseTaxonomyMetaBox.css', [ ADMINEASE_NAME . 'Global', ADMINEASE_NAME . 'NativeBox' ], filemtime( ADMINEASE_DIR . 'assets/css/AdminEaseTaxonomyMetaBox.css' ) ); wp_enqueue_script( ADMINEASE_NAME . 'TaxonomyMetaBox', ADMINEASE_PLUGIN_URL . 'assets/js/AdminEaseTaxonomyMetaBox.js', [ 'jquery' ], filemtime( ADMINEASE_DIR . 'assets/js/AdminEaseTaxonomyMetaBox.js' ), true ); wp_localize_script( ADMINEASE_NAME . 'TaxonomyMetaBox', ADMINEASE_NAME . 'TaxonomyMetaBoxAjaxObj', [ 'ajaxUrl' => admin_url( 'admin-ajax.php' ), 'security' => wp_create_nonce( 'adminease_taxonomy' ), 'termsPerPage' => self::TERMS_PER_PAGE, 'i18n' => [ 'loadingText' => esc_html__( 'Loading...', 'adminease' ), 'noResultsText' => esc_html__( 'No results found.', 'adminease' ), 'enterNewTermText' => esc_html__( 'Enter new term name', 'adminease' ), /* translators: %s is the taxonomy name */ 'removeSelected' => esc_html__( 'Remove %s', 'adminease' ), 'clearAll' => esc_html__( 'Clear all', 'adminease' ), /* translators: %d is the number of additional selected terms */ 'moreSelected' => esc_html__( '+%d more', 'adminease' ), /* translators: %s is the term name typed into the search box */ 'createTermLabel' => esc_html__( 'Create "%s"', 'adminease' ), 'errorLoadingTerms' => esc_html__( 'Error loading terms', 'adminease' ), 'errorLoadFailed' => esc_html__( 'Failed to load terms', 'adminease' ), 'searchFailed' => esc_html__( 'Search failed', 'adminease' ), 'searchNetworkError' => esc_html__( 'Search network error', 'adminease' ), 'termCreated' => esc_html__( 'Term created successfully!', 'adminease' ), /* translators: %s is the name of the term that was created */ 'termCreatedNamed' => esc_html__( 'Term %s created successfully!', 'adminease' ), 'createTermFailed' => esc_html__( 'Failed to create term', 'adminease' ), 'createTermNetworkError' => esc_html__( 'Network error while creating term', 'adminease' ), ], ] ); } /** * Replaces the default hierarchical taxonomy meta boxes with custom meta boxes. * This method removes the default WordPress meta boxes for hierarchical taxonomies * and adds custom ones with enhanced functionality for the specified taxonomies. * It only processes public, UI-visible, hierarchical taxonomies for the current post type. * @return void */ public function replace_taxonomy_meta_boxes(): void { $current_screen = get_current_screen(); if( !$current_screen || !in_array( $current_screen->base, [ 'post', 'post-new' ] ) ) { return; } $post_type = $current_screen->post_type; if( $this->is_gutenberg_enabled_for_post_type( $post_type ) ) { return; } $taxonomies = get_object_taxonomies( $post_type, 'objects' ); foreach( $taxonomies as $taxonomy => $tax_obj ) { if( !empty( $this->taxonomies ) && !in_array( $taxonomy, array_keys( $this->taxonomies ), true ) ) { continue; } if( !$tax_obj->public || !$tax_obj->show_ui ) { continue; } if( !$tax_obj->hierarchical ) { continue; } remove_meta_box( $taxonomy . 'div', $post_type, 'side' ); remove_meta_box( $taxonomy . 'div', $post_type, 'normal' ); add_meta_box( 'adminease-' . $taxonomy . 'div', $tax_obj->labels->name, [ $this, 'render_taxonomy_meta_box' ], $post_type, 'side', 'core', [ 'taxonomy' => $taxonomy ] ); } } /** * Check if Gutenberg (Block Editor) is enabled for a specific post type. * * @param string $post_type The post type to check. * * @return bool True if Gutenberg is enabled, false otherwise. */ private function is_gutenberg_enabled_for_post_type( string $post_type ): bool { if( !use_block_editor_for_post_type( $post_type ) ) { return false; } $can_edit = apply_filters( 'use_block_editor_for_post_type', true, $post_type ); // phpcs:ignore WordPress.NamingConventions.PrefixAllGlobals.NonPrefixedHooknameFound if( !$can_edit ) { return false; } if( function_exists( 'gutenberg_can_edit_post_type' ) ) { $gutenberg_can_edit = apply_filters( 'gutenberg_can_edit_post_type', true, $post_type ); // phpcs:ignore WordPress.NamingConventions.PrefixAllGlobals.NonPrefixedHooknameFound if( !$gutenberg_can_edit ) { return false; } } return true; } /** * Renders the taxonomy meta box for a specific taxonomy in the post edit screen. * This method outputs the HTML structure for displaying a taxonomy meta box, * including search input, terms tree, pagination controls, and a section * for creating a new term. It utilizes AJAX for dynamic loading and updating * of taxonomy terms based on user input. * * @param WP_Post $post The current post object being edited. * @param array $box An array containing the meta box arguments, particularly the 'taxonomy' key. * * @return void Does not return a value, output is handled via echo. */ public function render_taxonomy_meta_box( WP_Post $post, array $box ): void { $taxonomy = $box['args']['taxonomy']; $tax_obj = get_taxonomy( $taxonomy ); if( !$tax_obj ) { return; } $current_terms = wp_get_object_terms( $post->ID, $taxonomy ); if( is_wp_error( $current_terms ) ) { $current_terms = []; } wp_nonce_field( 'adminease_taxonomy_' . $taxonomy, 'adminease_taxonomy_nonce_' . $taxonomy ); ?>
esc_html__( 'Taxonomy does not exist', 'adminease' ) ] ); } $tax_obj = get_taxonomy( $taxonomy ); if( !$tax_obj || !$tax_obj->hierarchical ) { wp_send_json_error( [ 'message' => esc_html__( 'Only hierarchical taxonomies are supported', 'adminease' ) ] ); } $is_hierarchical = $tax_obj && $tax_obj->hierarchical; $args = [ 'taxonomy' => $taxonomy, 'hide_empty' => false, 'orderby' => 'name', 'order' => 'ASC', ]; if( !empty( $search ) ) { $args['name__like'] = $search; $args['number'] = $per_page; $args['offset'] = ( $page - 1 ) * $per_page; } else if( $is_hierarchical ) { $args['number'] = 0; } else { $args['number'] = $per_page; $args['offset'] = ( $page - 1 ) * $per_page; } $terms = get_terms( $args ); $count_args = [ 'taxonomy' => $taxonomy, 'hide_empty' => false, 'fields' => 'count', ]; if( !empty( $search ) ) { $count_args['name__like'] = $search; } $total_terms = get_terms( $count_args ); if( is_wp_error( $terms ) ) { wp_send_json_error( [ 'message' => $terms->get_error_message() ] ); } if( is_wp_error( $total_terms ) ) { $total_terms = 0; } if( $is_hierarchical && empty( $search ) ) { $hierarchy = $this->build_term_hierarchy( $terms ); $flat_terms = []; $this->flatten_hierarchy( $hierarchy, $flat_terms ); $display_terms = array_slice( $flat_terms, ( $page - 1 ) * $per_page, $per_page ); } else { $display_terms = $terms; } $post_id = intval( wp_unslash( $_POST['post_id'] ?? 0 ) ); $selected_terms = []; if( $post_id > 0 ) { $current_terms = wp_get_object_terms( $post_id, $taxonomy, [ 'fields' => 'ids' ] ); if( !is_wp_error( $current_terms ) ) { $selected_terms = $current_terms; } } $terms_html = $this->render_terms_html( $display_terms, $taxonomy, $is_hierarchical, $selected_terms ); $pagination_data = [ 'current_page' => $page, 'total_pages' => max( 1, (int) ceil( (int) $total_terms / $per_page ) ), 'total_items' => $total_terms, ]; $pagination_html = $this->render_pagination_html( $pagination_data ); $response_data = [ 'terms_html' => $terms_html, 'pagination_html' => $pagination_html, 'is_hierarchical' => $is_hierarchical, 'pagination' => $pagination_data, ]; wp_send_json_success( $response_data ); } /** * Handles the AJAX request for searching taxonomy terms. * This method processes incoming AJAX requests, validates the input data, * verifies the existence of the specified taxonomy, and retrieves a list * of matching taxonomy terms based on a search query. It also formats * and returns the retrieved terms in a JSON response. * @return void Sends a JSON response containing the search results, including * term details such as ID, name, slug, count, and parent, as well * as permission to create terms if applicable. Sends an error * */ public function ajax_search_taxonomy_terms(): void { if( !isset( $_POST['security'] ) || !wp_verify_nonce( sanitize_key( wp_unslash( $_POST['security'] ) ), 'adminease_taxonomy' ) ) { wp_send_json_error( new WP_Error( 'security_error', __( 'An error occurred. Refresh the page and try again.', 'adminease' ) ), 403 ); } $taxonomy = sanitize_text_field( wp_unslash( $_POST['taxonomy'] ?? '' ) ); $search = sanitize_text_field( wp_unslash( $_POST['search'] ?? '' ) ); if( !taxonomy_exists( $taxonomy ) ) { wp_send_json_error( [ 'message' => esc_html__( 'Taxonomy does not exist', 'adminease' ) ] ); } $tax_obj = get_taxonomy( $taxonomy ); $args = [ 'taxonomy' => $taxonomy, 'hide_empty' => false, 'orderby' => 'name', 'order' => 'ASC', 'number' => 50, ]; if( !empty( $search ) ) { $args['name__like'] = $search; } $terms = get_terms( $args ); if( is_wp_error( $terms ) ) { wp_send_json_error( [ 'message' => $terms->get_error_message() ] ); } $post_id = isset( $_POST['post_id'] ) ? absint( wp_unslash( $_POST['post_id'] ) ) : 0; $selected_terms = []; if( $post_id > 0 ) { $current_terms = wp_get_object_terms( $post_id, $taxonomy, [ 'fields' => 'ids' ] ); if( !is_wp_error( $current_terms ) ) { $selected_terms = $current_terms; } } $response = [ 'terms_html' => $this->render_terms_html( $terms, $taxonomy, false, $selected_terms ), 'count' => count( $terms ), 'search_term' => $search, 'can_create' => current_user_can( $tax_obj->cap->edit_terms ?? 'manage_categories' ), ]; wp_send_json_success( $response ); } /** * Handles the AJAX request to create a new taxonomy term. * This method processes incoming AJAX requests, validates the input, verifies * the taxonomy, checks user permissions, and creates a new term with the provided * data. It returns the created term's data as a response or an error message if * the creation fails. * @return void Sends a JSON response with the created term's data upon successful * execution or an error message in case of failure. */ public function ajax_create_taxonomy_term(): void { if( !isset( $_POST['security'] ) || !wp_verify_nonce( sanitize_key( wp_unslash( $_POST['security'] ) ), 'adminease_taxonomy' ) ) { wp_send_json_error( new WP_Error( 'security_error', __( 'An error occurred. Refresh the page and try again.', 'adminease' ) ), 403 ); } $taxonomy = sanitize_text_field( wp_unslash( $_POST['taxonomy'] ?? '' ) ); $term_name = sanitize_text_field( wp_unslash( $_POST['term_name'] ?? '' ) ); $parent_id = intval( sanitize_text_field( wp_unslash( $_POST['parent_id'] ?? 0 ) ) ); if( !taxonomy_exists( $taxonomy ) ) { wp_send_json_error( [ 'message' => esc_html__( 'Taxonomy does not exist', 'adminease' ) ] ); } if( empty( $term_name ) ) { wp_send_json_error( [ 'message' => esc_html__( 'Term name is required', 'adminease' ) ] ); } $tax_obj = get_taxonomy( $taxonomy ); if( !current_user_can( $tax_obj->cap->edit_terms ?? 'manage_categories' ) ) { wp_send_json_error( [ 'message' => esc_html__( 'You do not have permission to create terms', 'adminease' ) ] ); } $args = [ 'parent' => $parent_id ]; $result = wp_insert_term( $term_name, $taxonomy, $args ); if( is_wp_error( $result ) ) { wp_send_json_error( [ 'message' => $result->get_error_message() ] ); } $term = get_term( $result['term_id'], $taxonomy ); if( is_wp_error( $term ) ) { wp_send_json_error( [ 'message' => esc_html__( 'Failed to retrieve created term', 'adminease' ) ] ); } $response = [ 'id' => $term->term_id, 'name' => $term->name, 'slug' => $term->slug, 'parent' => $term->parent, ]; wp_send_json_success( $response ); } /** * Handles the AJAX request to get term names for specific term IDs. * This method is used to populate selected term names when the page loads. * @return void Sends a JSON response with term names. */ public function ajax_get_term_names(): void { if( !isset( $_POST['security'] ) || !wp_verify_nonce( sanitize_key( wp_unslash( $_POST['security'] ) ), 'adminease_taxonomy' ) ) { wp_send_json_error( new WP_Error( 'security_error', __( 'An error occurred. Refresh the page and try again.', 'adminease' ) ), 403 ); } $taxonomy = sanitize_text_field( wp_unslash( $_POST['taxonomy'] ?? '' ) ); $term_ids = array_map( 'intval', wp_unslash( $_POST['term_ids'] ?? [] ) ); if( !taxonomy_exists( $taxonomy ) ) { wp_send_json_error( [ 'message' => esc_html__( 'Taxonomy does not exist', 'adminease' ) ] ); } if( empty( $term_ids ) ) { wp_send_json_error( [ 'message' => esc_html__( 'No term IDs provided', 'adminease' ) ] ); } $terms_data = []; foreach( $term_ids as $term_id ) { $term = get_term( $term_id, $taxonomy ); if( !is_wp_error( $term ) && $term ) { $terms_data[] = [ 'id' => $term->term_id, 'name' => $term->name, ]; } } wp_send_json_success( [ 'terms' => $terms_data ] ); } /** * Generates and returns the HTML markup for a list of taxonomy terms. * This method creates an HTML structure for displaying terms in either * hierarchical or non-hierarchical format, including options for selecting terms * and rendering depth indicators for hierarchical terms. * * @param array $terms An array of term objects to be rendered. * @param string $taxonomy The taxonomy slug associated with the terms. * @param bool $is_hierarchical Whether the taxonomy is hierarchical. * @param array $selected_terms Optional. An array of term IDs that should be pre-selected. * Defaults to an empty array. * * @return string The generated HTML markup for the terms list. */ private function render_terms_html( array $terms, string $taxonomy, bool $is_hierarchical, array $selected_terms = [] ): string { ob_start(); ?>