Dog Breeds Select2 Metabox Plugin

This file is a WordPress plugin that introduces a custom metabox to the Dog post type using Select2 for an enhanced user interface. It allows users to select dog breeds from a custom taxonomy with a searchable dropdown, which supports multiple selections and lazy loading for performance. The plugin also includes scripts for enqueuing Select2 assets and functions for saving the selected terms.

<?php /* Plugin Name: Dog Breeds Metabox with Select2 Description: A metabox using Select2 for Dog post type, with lazy loaded choices from dog_breeds taxonomy. Version: 1.0 Author: Your Name */ function codewp_enqueue_select2() { wp_enqueue_style('select2', ''); wp_enqueue_script('select2', '', array('jquery'), '4.0.13', true); } add_action( 'admin_enqueue_scripts', 'codewp_enqueue_select2' ); function codewp_dog_breeds_metabox() { add_meta_box( 'dog_breeds_metabox', 'Dog Breeds', 'codewp_dog_breeds_metabox_callback', 'dog', 'side', 'default' ); } add_action('add_meta_boxes', 'codewp_dog_breeds_metabox'); function codewp_dog_breeds_metabox_callback($post) { wp_nonce_field(basename(__FILE__), 'codewp_nonce'); $dog_breeds = get_terms('dog_breeds', array('hide_empty' => false)); $selected_breeds = get_the_terms($post->ID, 'dog_breeds'); $selected_breeds_ids = ($selected_breeds) ? array_map(function($term) { return $term->term_id; }, $selected_breeds) : array(); ?> <select id="select2-dog-breeds" name="dog_breeds[]" multiple="multiple" style="width: 100%;"> <?php foreach ($dog_breeds as $breed) : ?> <option value="<?php echo $breed->term_id; ?>" <?php echo (in_array($breed->term_id, $selected_breeds_ids)) ? 'selected' : ''; ?>><?php echo $breed->name; ?></option> <?php endforeach; ?> </select> <script type="text/javascript"> jQuery(document).ready(function($) { $('#select2-dog-breeds').select2({ minimumInputLength: 2, matcher: function(params, data) { if ($.trim(params.term) === '') { return data; } if (data.text.toLowerCase().indexOf(params.term.toLowerCase()) > -1) { var modifiedData = $.extend({}, data, true); return modifiedData; } return null; } }); }); </script> <?php } function codewp_save_dog_breeds_metabox($post_id, $post) { if (!isset($_POST['codewp_nonce']) || !wp_verify_nonce($_POST['codewp_nonce'], basename(__FILE__))) return $post_id; $dog_breeds = (isset($_POST['dog_breeds'])) ? $_POST['dog_breeds'] : array(); wp_set_object_terms($post_id, $dog_breeds, 'dog_breeds'); } add_action('save_post', 'codewp_save_dog_breeds_metabox', 10, 2); function codewp_remove_default_dog_breeds_metabox() { remove_meta_box('tagsdiv-dog_breeds', 'dog', 'side'); } add_action('admin_menu', 'codewp_remove_default_dog_breeds_metabox'); ?>

Frequently Asked Questions

This plugin adds a custom Select2 metabox to the Dog post type for selecting dog breeds from the taxonomy.