How to Add a Category Search Box to WooCommerce Product Editor?


Navigating through a long list of categories while creating a new post or product in WordPress can be time-consuming and frustrating. Finding the right one quickly becomes a challenge if you’re managing a blog or an online shop with numerous categories. In this guide, I’ll show you how to add a search field to the category selection box in the WordPress post editor, making your content creation process smoother and more efficient.

The Challenge: Navigating Through Numerous Categories

As your website grows, so does the number of categories you use to organize your content or products. Scrolling through an extensive list to find the appropriate category can slow down your workflow and lead to mistakes if the wrong category is selected.

The Solution: Adding a Category Search Field

By implementing a category search field in the post editor, you can easily search and select the desired categories without scrolling through the entire list. This enhancement filters the categories in real-time as you type, displaying only those that match your search term.

What Does This Solution Do?

  • Adds a search box above your category selection area
  • Filters categories in real-time as you type
  • Works for both regular post categories and WooCommerce product categories
  • Includes a convenient “Clear Search” button
  • Keeps checked categories visible even when filtered
  • Fully accessible and mobile-friendly
How to Add a Category Search Box to WooCommerce Product Editor

Benefits for Shop Users

If your WordPress site has dozens or hundreds of categories, finding the right one can be like searching for a needle in a haystack. This enhancement makes category management much more efficient, saving you valuable time when creating or editing posts and products.

  • Time-Saving: Quickly find and select categories, speeding up the content creation process.
  • Improved Accuracy: Reduce the chances of assigning the wrong categories to posts or products.
  • Enhanced User Experience: Streamline your workflow, making content management more enjoyable.

Video: How to Add a Category Search Box to WooCommerce Product Editor?

How to Implement the Woocommerce Product Editor Category Search Field?

There are three simple methods to add this functionality to your WordPress site:

Option 1: Using the Code Snippets Plugin

The Code Snippets plugin allows you to add custom code to your site without editing your theme files. It’s safer and ensures that your customizations remain intact even if you switch themes.

Steps:

1. Install the Code Snippets Plugin:

  • Go to your WordPress dashboard.
  • Navigate to Plugins > Add New.
  • Search for “Code Snippets”.
  • Click Install Now and then Activate.

2. Add the Custom Code:

  • Go to Snippets > Add New.
  • Give your snippet a title, like “Category Search Field”.
  • Paste the following code into the code box:
<?php
/**
 * Plugin Name: WooCommerce Category Search
 * Plugin URI: https://wpsimplehacks.com
 * Description: Adds a search box to WooCommerce product category selection for easier category management.
 * Version: 1.0.0
 * Author: WP Simple Hacks
 * Author URI: https://wpsimplehacks.com
 * License: GPL v2 or later
 * License URI: https://www.gnu.org/licenses/gpl-2.0.html
 * Text Domain: woocommerce-category-search
 * Domain Path: /languages
 * Requires at least: 5.0
 * Tested up to: 6.3
 * Requires PHP: 7.4
 * WC requires at least: 3.0
 * WC tested up to: 8.0
 */

// Prevent direct access
if (!defined('ABSPATH')) {
    exit;
}

// Define plugin constants
define('WCCS_VERSION', '1.0.0');
define('WCCS_PLUGIN_URL', plugin_dir_url(__FILE__));
define('WCCS_PLUGIN_PATH', plugin_dir_path(__FILE__));

/**
 * Main plugin class
 */
class WooCommerce_Category_Search {
    
    /**
     * Initialize the plugin
     */
    public function __construct() {
        add_action('init', array($this, 'init'));
        register_activation_hook(__FILE__, array($this, 'activate'));
        register_deactivation_hook(__FILE__, array($this, 'deactivate'));
    }
    
    /**
     * Initialize plugin functionality
     */
    public function init() {
        // Load text domain for translations
        load_plugin_textdomain('woocommerce-category-search', false, dirname(plugin_basename(__FILE__)) . '/languages');
        
        // Add the search functionality only in admin
        if (is_admin()) {
            add_action('admin_print_footer_scripts', array($this, 'add_category_search_field'));
        }
    }
    
    /**
     * Plugin activation
     */
    public function activate() {
        // Check WordPress version
        if (version_compare(get_bloginfo('version'), '5.0', '<')) {
            deactivate_plugins(plugin_basename(__FILE__));
            wp_die(__('This plugin requires WordPress 5.0 or higher.', 'woocommerce-category-search'));
        }
        
        // Check if WooCommerce is active
        if (!$this->is_woocommerce_active()) {
            deactivate_plugins(plugin_basename(__FILE__));
            wp_die(__('This plugin requires WooCommerce to be installed and active.', 'woocommerce-category-search'));
        }
    }
    
    /**
     * Plugin deactivation
     */
    public function deactivate() {
        // Cleanup if needed
    }
    
    /**
     * Check if WooCommerce is active
     */
    private function is_woocommerce_active() {
        return class_exists('WooCommerce') || in_array('woocommerce/woocommerce.php', apply_filters('active_plugins', get_option('active_plugins')));
    }
    
    /**
     * Add category search field to product editor
     */
    public function add_category_search_field() {
        global $pagenow, $post;
        
        // Only show on post edit pages and for products
        if (!in_array($pagenow, ['post.php', 'post-new.php'])) {
            return;
        }
        
        // Check if we're editing a product
        if (isset($post) && $post->post_type !== 'product') {
            return;
        }
        
        // Check if WooCommerce is active
        if (!$this->is_woocommerce_active()) {
            return;
        }
        
        // Get internationalized strings
        $search_placeholder = esc_attr__('Search categories...', 'woocommerce-category-search');
        $clear_search_text = esc_html__('Clear Search', 'woocommerce-category-search');
        $search_label = esc_attr__('Search product categories', 'woocommerce-category-search');
        $clear_label = esc_attr__('Clear category search', 'woocommerce-category-search');
        ?>
        <style type="text/css">
            .wccs-category-search {
                margin-bottom: 10px;
                width: 100%;
                padding: 6px 8px;
                border: 1px solid #ddd;
                border-radius: 4px;
                font-size: 14px;
            }
            .wccs-category-search:focus {
                border-color: #007cba;
                outline: none;
                box-shadow: 0 0 0 1px #007cba;
            }
            .wccs-clear-search {
                margin-bottom: 10px;
                font-size: 12px;
            }
            .wccs-search-container {
                border-bottom: 1px solid #eee;
                padding-bottom: 10px;
                margin-bottom: 10px;
            }
            .wccs-no-results {
                padding: 10px;
                color: #666;
                font-style: italic;
                display: none;
            }
        </style>
        <script type="text/javascript">
            jQuery(document).ready(function($) {
                // Target both default and product category boxes
                var categoryBoxes = $('#categorydiv .inside, #product_catdiv .inside');
                
                categoryBoxes.each(function() {
                    var categoryBox = $(this);
                    var checklist = categoryBox.find('.categorychecklist, .categorychecklist-holder');
                    
                    // Add search container with improved styling
                    var searchContainer = $(`
                        <div class="wccs-search-container">
                            <input type="text" class="wccs-category-search" placeholder="<?php echo $search_placeholder; ?>" aria-label="<?php echo $search_label; ?>" />
                            <button type="button" class="button wccs-clear-search" aria-label="<?php echo $clear_label; ?>"><?php echo $clear_search_text; ?></button>
                        </div>
                        <div class="wccs-no-results"><?php echo esc_html__('No categories found matching your search.', 'woocommerce-category-search'); ?></div>
                    `);
                    
                    categoryBox.prepend(searchContainer);
                });
                
                var debounceTimeout;
                var searchCache = {};
                
                // Enhanced search function with debounce and caching
                $('.wccs-category-search').on('keyup input', function() {
                    var searchInput = $(this);
                    var categoryBox = searchInput.closest('.inside');
                    var searchTerm = searchInput.val().toLowerCase().trim();
                    
                    clearTimeout(debounceTimeout);
                    debounceTimeout = setTimeout(function() {
                        performSearch(categoryBox, searchTerm);
                    }, 200);
                });
                
                // Enhanced search function
                function performSearch(categoryBox, searchTerm) {
                    var items = categoryBox.find('.categorychecklist li');
                    var visibleCount = 0;
                    var noResultsDiv = categoryBox.find('.wccs-no-results');
                    
                    if (searchTerm === '') {
                        items.show();
                        noResultsDiv.hide();
                        return;
                    }
                    
                    items.each(function() {
                        var item = $(this);
                        var categoryName = item.find('label').text().toLowerCase();
                        var isChecked = item.find('input[type="checkbox"]').is(':checked');
                        
                        // Show if matches search or is checked
                        if (categoryName.indexOf(searchTerm) !== -1 || isChecked) {
                            item.show();
                            visibleCount++;
                        } else {
                            item.hide();
                        }
                    });
                    
                    // Show/hide no results message
                    if (visibleCount === 0) {
                        noResultsDiv.show();
                    } else {
                        noResultsDiv.hide();
                    }
                }
                
                // Clear search functionality
                $('.wccs-clear-search').on('click', function() {
                    var categoryBox = $(this).closest('.inside');
                    var searchInput = categoryBox.find('.wccs-category-search');
                    
                    searchInput.val('').focus();
                    categoryBox.find('.categorychecklist li').show();
                    categoryBox.find('.wccs-no-results').hide();
                });
                
                // Add keyboard shortcuts
                $('.wccs-category-search').on('keydown', function(e) {
                    // Clear on Escape
                    if (e.keyCode === 27) {
                        $(this).closest('.inside').find('.wccs-clear-search').click();
                    }
                });
                
                // Auto-focus search when category metabox is opened
                $(document).on('click', '.handlediv', function() {
                    var metabox = $(this).closest('.postbox');
                    if (metabox.find('.wccs-category-search').length) {
                        setTimeout(function() {
                            metabox.find('.wccs-category-search').focus();
                        }, 100);
                    }
                });
            });
        </script>
        <?php
    }
}

// Initialize the plugin
new WooCommerce_Category_Search();

3. Choose “Only run in administration area”, then Save and Activate:

Option 2: Using the functions.php of Your Child Theme

⚠️ Warning: This method requires more technical knowledge and can break your site if not done carefully!

If you’re comfortable editing theme files, you can add the code directly to your child theme’s functions.php file.

Steps:

1. Access Your Child Theme’s functions.php:

  • Use FTP or the WordPress Theme Editor (Appearance > Theme Editor).

2. Add the Custom Code:. Paste the same code provided above at the end of the functions.php file.

3. Save the Changes.

Note: Editing the functions.php file can break your site if not done correctly. Always back up your site before making changes.

Why Using Code Snippets Is Better Than Editing functions.php

  • Safety: Mistakes in functions.php can cause site errors. Code Snippets isolates custom code, reducing risk.
  • Portability: Snippets remain active even if you switch or update themes. Also, there is no risk of breaking your theme during updates
  • Organization: Easy to enable/disable without editing files. You can easily manage and organize all your custom code in one place.
  • No Need for FTP: Add and edit code directly from the WordPress dashboard.

Option 3: Installing the Downloadable Plugin (Easiest)

For the easiest implementation, you can install the pre-packaged plugin version of this code.

1. Download the plugin

    2. Install the Plugin:

    • Go to your WordPress dashboard.
    • Navigate to Plugins > Add New.
    • Click on Upload Plugin.
    • Choose the downloaded .zip file and click Install Now.

    3. Activate the Plugin.

    How It Works?

    Once installed, you’ll see a search box appear above your category list when editing any post or product. Simply:

    1. Start typing the category name you’re looking for
    2. The list will automatically filter to show matching categories
    3. Click the checkbox next to the category you want
    4. Use the “Clear Search” button to reset the filter

    Pro Tips

    • The search is instant – no need to press Enter
    • Already checked categories remain visible even when filtering
    • The search is case-insensitive, so “SHOES” and “shoes” will find the same categories
    • Works perfectly on both desktop and mobile devices

    Troubleshooting

    If you don’t see the search box:

    1. Make sure you’re on a product editing screen
    2. Try clearing your browser cache
    3. Check if your theme has any conflicts with jQuery
    4. Verify that the code is properly activated

    Conclusion

    This simple enhancement can save you countless minutes of scrolling and searching through categories. Whether you’re managing a small blog or a large e-commerce site, having a searchable category box makes content management significantly easier.

    Do you want to thank me and buy me a beer?

    Every donation is entirely welcome but NEVER required. Enjoy my work for free but if you would like to thank me and buy me a beer or two then you can use this form here below.

    Donation Form (#2)

    Here are some of my favorite WordPress tools

    Thanks for reading this article! I hope it's been useful as you work on your own websites and e-commerce sites. I wanted to share some tools I use as a WordPress developer, and I think you'll find them helpful too.

    Just so you know, these are affiliate links. If you decide to use any of them, I'll earn a commission. This helps me create tutorials and YouTube videos. But honestly, I genuinely use and recommend these tools to my friends and family as well. Your support keeps me creating content that benefits everyone.

    Themes: Over the past few years, I've consistently relied on two primary themes for all sorts of projects: the Blocksy theme and the Kadence Theme. If you explore this website and my YouTube channel, you'll come across numerous tutorials that delve into these themes. If you're interested in obtaining a 10% discount for both of these themes, then:

    Code Snippets Manager: WPCodeBox allows you to add code snippets to your site. Not only that, but it also provides you with the capability to construct and oversee your WordPress Code Snippets library right in the cloud. You can grab it with the 20% discount here (SAVE 20% Coupon: WPSH20).

    Contact forms: There are hundreds of contact forms out there but Fluent Forms is the one I like the most. If you need a 20% discount then use this link (save 20% coupon is WPSH20).

    Gutenberg add-ons: If I need a good Gutenberg blocks add-on then Kadence Blocks is the one I have used the most. You’ll get a 10% discount with the coupon SIMPLEHACKS here.

    Website migration: While building a website you probably need a good plugin that can help you with the migration, backups, restoration, and staging sites. Well, WpVivid is the one I have used for the last couple of years. If you use this link along with the WPSH20 coupon you’ll get a 20% discount.

    Woocommerce extensions: There are a bunch of Woocommerce extensions that I like but the one that stands out is Advanced Dynamic Pricing. Once again, you’ll get a 20% discount if you use this link here (save 20% coupon is WPSH20)

    Web Hosting: If you would like to have a really fast and easy-to-use managed cloud hosting, then I recommend Verpex Hosting (see my review here). By the way, this site is hosted in Verpex.)

    To see all my most up-to-date recommendations, check out this resource that I made for you!

    Janek T.
    Janek T.

    - I have been passionate about Wordpress since 2011, creating websites and sharing valuable tips on using Wordpress and Woocommerce on my site.
    - Be the first to receive notifications about new tutorials by subscribing to my Youtube channel .
    - Follow me on Twitter here

    Articles: 162