我正在尝试为类别添加自定义字段。自定义字段是一个复选框。我可以让复选框显示在“创建新类别”和“编辑类别”页面中的表单上,但如果选中复选框,则在保存表单后不会保持选中状态。
这是我正在使用的代码:
/* Custom Field for Categories.
======================================== */
//Add new page
function my_taxonomy_add_meta_fields( $taxonomy ) {
?>
<div class="form-field term-group">
<label for="show_category"><?php _e( \'Show Category\', \'codilight-lite\' ); ?></label>
<input type="checkbox" id="show_category" name="show_category" />
</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="<?php echo $show_category; ?>" />
</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\', esc_attr( $_POST[\'show_category\'] ) );
}
}
add_action( \'created_category\', \'my_taxonomy_save_taxonomy_meta\', 10, 2 );
add_action( \'edited_category\', \'my_taxonomy_save_taxonomy_meta\', 10, 2 );
我从找到的教程中复制了这段代码。原始代码用于文本字段类型的自定义字段,因此我认为问题可能与复选框设置有关。