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.