// 添加分类图像字段
// 这段代码将在分类添加页面中添加一个名为“Category Image”的自定义字段。
// 编写自定义代码:如果您愿意编写自己的代码,可以按照以下步骤进行操作:
// a. 打开主题的functions.php文件。
// b. 添加以下代码:
// 添加自定义字段到分类
function wp_add_custom_category_fields( $taxonomy ) {
?>
<div class="form-field">
<label for="custom_field">自定义字段</label>
<input type="text" name="custom_field" id="custom_field">
<p class="description">输入自定义字段的值。</p>
</div>
<?php
}
add_action( 'category_add_form_fields', 'wp_add_custom_category_fields', 10, 2 );
// 保存自定义字段的值
function wp_save_custom_category_fields( $term_id, $tt_id ) {
if ( isset( $_POST['custom_field'] ) ) {
$custom_field = sanitize_text_field( $_POST['custom_field'] );
update_term_meta( $term_id, 'custom_field', $custom_field );
}
}
add_action( 'created_category', 'wp_save_custom_category_fields', 10, 2 );
// 编辑页面中显示自定义字段的值
function wp_edit_custom_category_fields( $term ) {
$custom_field = get_term_meta( $term->term_id, 'custom_field', true );
?>
<tr class="form-field">
<th scope="row" valign="top">
<label for="custom_field">自定义字段</label>
</th>
<td>
<input type="text" name="custom_field" id="custom_field" value="<?php echo esc_attr( $custom_field ); ?>">
<p class="description">输入自定义字段的值。</p>
</td>
</tr>
<?php
}
add_action( 'category_edit_form_fields', 'wp_edit_custom_category_fields', 10, 2 );
// 更新自定义字段的值
function wp_update_custom_category_fields( $term_id ) {
if ( isset( $_POST['custom_field'] ) ) {
$custom_field = sanitize_text_field( $_POST['custom_field'] );
update_term_meta( $term_id, 'custom_field', $custom_field );
}
}
add_action( 'edited_category', 'wp_update_custom_category_fields', 10, 2 );