Prevent checked categories in meta box from appearing at top in WordPress

Squared notebook with a checklist on one of the pages.
Tracing boxes to create checkboxes is soothing.

I previously shared a jQuery snippet that enforces parent checkboxes to be checked when a child is checked and children to be unchecked if the parent is unchecked.

This works really great in theory, except that WordPress, by default, moves all checked checkboxes to the top of the category list, which effectively breaks the JavaScript snippet because it depends on the hierarchy.

If enforcing the checkboxes is more important to you than how they are visually displayed, here’s a WordPress filter that lets you prevent checked checkboxes from moving to the top.

add_filter(
  'wp_terms_checklist_args',
  NS . 'wp_terms_checklist_args'
);

function wp_terms_checklist_args($args) {
  $args['checked_ontop'] = false;
  return $args;
}

The constant NS is what I use to maintain namespaces in the plugins I write. This ensures compatibility without having to write crazy long function names or create a class just for the sake of name-spacing.

Featured image by Glenn Carstens-Peters.


Comments (4)

Previously posted in WordPress and transferred to Ghost.

Attila
March 25, 2014 at 11:03 am

Hello,
thanks for this!
I have several child categories with the same name, so it was really confusing when they moved on top.
Strange feature.. anyway thanks!

makinero
May 31, 2017 at 3:55 am

I think the code is buggy.

I had to replace this :

NS . 'wp_terms_checklist_args'

by this :

'wp_terms_checklist_args' (removing the NS.) in order to make it work.

Ryan Sechrest
May 31, 2017 at 9:49 am

You’re right, if you don’t set it up how I explained it in the linked article above, your code works just as well. I can see how that would be confusing.

larssg
February 9, 2021 at 8:58 pm

Unfortunately, this breaks custom taxonomies and just replaces them with your posts categories.