Prevent Selected Terms Rising to the Top

When you’re editing a post and select a child category or term, and update, the selected terms appear at the top ( leading to potentially confusing situations where ‘foo’ ‘foo’ and ‘foo’ are selected each with different parents and no way to tell them apart ).

How do I prevent this behaviour? Either by showing the parent terms to give context, or stopping them being moved to the top

2 Answers
2

This bugs me too. It is very confusing, so I thought I’d look into it.

That meta box is created in “wp-admin/includes/meta-boxes.php” on line ~399. It uses wp_terms_checklist. The problem codes seems to be this (it is one in source):

<?php wp_terms_checklist(
    $post->ID, array( 
        'taxonomy' => $taxonomy, 
        'popular_cats' => $popular_ids 
) ) ?>

That leaves a couple of options that I can think of.

You could use Javascript to reorder the list. You can’t remove the oddball categories because they won’t be available in the list. But I doubt that would be either quick or easy.

Or, you can remove the default box with remove_meta_box and add back a near clone with add_meta_box altering the line above to be:

<?php wp_terms_checklist(
    $post->ID, 
    array( 
        'taxonomy' => $taxonomy,
        'popular_cats' => $popular_ids 
        'check_ontop' => false 
) ) ?>

The checked_ontop part is the key. Removing and adding a metabox seems a long way to go to add those few characters and I sort-of hate to do it because it is pretty close to a core hack (but isn’t 🙂 ), though changes to the core could mean a need to rewrite that function. I don’t think there is any other real option though.

EDIT: OK. I originally thought that there was no hook that would help with this but there is one. All you need is:

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

That is going to alter things globally so it may be necessary to alter that so that it only runs on particular pages.

Thanks to Tom J Nowell. Sometimes it is good to be wrong.

Leave a Comment