复选框与文本输入略有不同。下面的主要更改是保存功能和处理checked 属性的价值show_category 如果已选中,则为“是”,如果未选中,则为空字符串。
请记住,如果show_category meta从未保存过,它将被取消设置,所以请在代码中考虑这一点。
/*  Custom Field for Categories.
    ======================================== */
// Add new term page
function my_taxonomy_add_meta_fields( $taxonomy ) { ?>
    <div class="form-field term-group">
        <label for="show_category">
          <?php _e( \'Show Category\', \'codilight-lite\' ); ?> <input type="checkbox" id="show_category" name="show_category" value="yes" />
        </label>
    </div><?php
}
add_action( \'category_add_form_fields\', \'my_taxonomy_add_meta_fields\', 10, 2 );
// Edit term page
function my_taxonomy_edit_meta_fields( $term, $taxonomy ) {
    $show_category = get_term_meta( $term->term_id, \'show_category\', true ); ?>
    <tr class="form-field term-group-wrap">
        <th scope="row">
            <label for="show_category"><?php _e( \'Show Category\', \'codilight-lite\' ); ?></label>
        </th>
        <td>
            <input type="checkbox" id="show_category" name="show_category" value="yes" <?php echo ( $show_category ) ? checked( $show_category, \'yes\' ) : \'\'; ?>/>
        </td>
    </tr><?php
}
add_action( \'category_edit_form_fields\', \'my_taxonomy_edit_meta_fields\', 10, 2 );
// Save custom meta
function my_taxonomy_save_taxonomy_meta( $term_id, $tag_id ) {
    if ( isset( $_POST[ \'show_category\' ] ) ) {
        update_term_meta( $term_id, \'show_category\', \'yes\' );
    } else {
        update_term_meta( $term_id, \'show_category\', \'\' );
    }
}
add_action( \'created_category\', \'my_taxonomy_save_taxonomy_meta\', 10, 2 );
add_action( \'edited_category\', \'my_taxonomy_save_taxonomy_meta\', 10, 2 );