こんにちは、asです。
先日、WordPress案件で親カテゴリーを選択不可にする必要があったので調べました。
その忘備録です(^^)
注意点としては、クラシックエディターのみの対応ということです(ブロックエディターには非対応)。

手順とコード

WordPressで親子カテゴリーがある際に、親カテゴリーを選択できないようにするコードです。
構築のしやすさで親カテゴリーでまとめたけど、選択はしたくないという時などに。

通常投稿のカテゴリーの他、カスタム投稿タイプのカスタムタクソノミーでも使用できます。
コードは編集箇所もなく、functions.phpにコピペするだけでオーケーです(^^)


image

親カテゴリーがグレーアウトして選択できなくなりました。
子カテゴリーのないものはそのままです。
functions.phpは編集したら、一度管理画面のパーマリンク設定を更新してください

コピペ用コード


/* ------------------------------------------------------------------------------ 
	親カテゴリー・親タームを選択できないようにする
------------------------------------------------------------------------------ */
require_once(ABSPATH . '/wp-admin/includes/template.php');
class Nocheck_Category_Checklist extends Walker_Category_Checklist {

  function start_el( &$output, $category, $depth = 0, $args = array(), $id = 0 ) {
    extract($args);
    if ( empty( $taxonomy ) )
      $taxonomy = 'category';

    if ( $taxonomy == 'category' )
      $name = 'post_category';
    else
      $name = 'tax_input['.$taxonomy.']';

    $class = in_array( $category->term_id, $popular_cats ) ? ' class="popular-category"' : '';
    $cat_child = get_term_children( $category->term_id, $taxonomy );

    if( !empty( $cat_child ) ) {
      $output .= "\n<li id='{$taxonomy}-{$category->term_id}'$class>" . '<label class="selectit"><input value="' . $category->term_id . '" type="checkbox" name="'.$name.'[]" id="in-'.$taxonomy.'-' . $category->term_id . '"' . checked( in_array( $category->term_id, $selected_cats ), true, false ) . disabled( empty( $args['disabled'] ), true, false ) . ' /> ' . esc_html( apply_filters('the_category', $category->name )) . '</label>';
    } else {
      $output .= "\n<li id='{$taxonomy}-{$category->term_id}'$class>" . '<label class="selectit"><input value="' . $category->term_id . '" type="checkbox" name="'.$name.'[]" id="in-'.$taxonomy.'-' . $category->term_id . '"' . checked( in_array( $category->term_id, $selected_cats ), true, false ) . disabled( empty( $args['disabled'] ), false, false ) . ' /> ' . esc_html( apply_filters('the_category', $category->name )) . '</label>';
    }
  }

}

function wp_category_terms_checklist_no_top( $args, $post_id = null ) {
  $args['checked_ontop'] = false;
  $args['walker'] = new Nocheck_Category_Checklist();
  return $args;
}
add_action( 'wp_terms_checklist_args', 'wp_category_terms_checklist_no_top' );