• omarbaradia

    (@omarbaradia)


    Hello, I have more than 150 categories and subcategories, and I need this number due to the nature of my site, but I am facing a problem in searching for the appropriate category while writing the article. Is there a way to hide the subcategories, so that the subcategories do not appear until after choosing the main category?

Viewing 3 replies - 1 through 3 (of 3 total)
  • Harsh Gajipara

    (@harshgajipara)

    Hi @omarbaradia,
    In WordPress, the default behavior is to display all categories and subcategories when assigning a category to a post. However, you can use JavaScript or jQuery to modify the admin category selection interface to achieve what you’re looking for.

    WordPress provides hooks and actions to enqueue scripts and styles in the admin area. You can use these to include your JavaScript/jQuery file.

    jQuery(document).ready(function($) {
        // Hide all subcategories initially
        $('#categorychecklist input[type="checkbox"]').each(function() {
            if ($(this).parent().hasClass('children')) {
                $(this).hide();
            }
        });
    
        // Show subcategories when a main category is selected
        $('#categorychecklist input[type="checkbox"]').change(function() {
            if ($(this).parent().hasClass('category')) {
                var mainCatID = $(this).val();
                $('input[type="checkbox"][value^="' + mainCatID + '"]').show();
            }
        });
    });
    

    Paste the provided code in a .js file (e.g., hide-subcategories.js).

    Add the following code in your theme’s functions.php file

    function enqueue_hide_subcategories_script() {
        wp_enqueue_script('hide-subcategories', get_template_directory_uri() . '/js/hide-subcategories.js', array('jquery'), '1.0', true);
    }
    add_action('admin_enqueue_scripts', 'enqueue_hide_subcategories_script');
    

    Please replace 'get_template_directory_uri() . '/js/hide-subcategories.js' with the actual path to your JavaScript file if it’s in a different directory.

    Thread Starter omarbaradia

    (@omarbaradia)

    Thanks @harshgajipara

    I tried this method but no change occurred!

    Moderator bcworkz

    (@bcworkz)

    Harsh’s approach is valid, but properly implementing it can be tricky, it’s somewhat error prone to implement. I’ve not verified if the error is theirs or yours but there is an alternative approach. You can use the “pre_get_terms” action to set the “parent” query var to 0, which will cause the query to only return top level terms.

    All term queries pass through this action, so you’ll need to apply this conditionally, such as only for admin requests for the category taxonomy.

Viewing 3 replies - 1 through 3 (of 3 total)
  • The topic ‘How can I separate categories when writing a new article?’ is closed to new replies.