Category分类管理页面添加字段
wptutor
2023-11-21
42 Views
<?php // Add custom field to category add new screen
function add_category_custom_fields() {
?>
<div class="form-field">
<label for="custom_field"><?php _e('Custom Field'); ?></label>
<input type="text" name="custom_field" id="custom_field" value="">
<p class="description"><?php _e('Enter custom field value here.'); ?></p>
</div>
<?php
}
add_action('category_add_form_fields', 'add_category_custom_fields');
// Save custom field value when a new category is created
function save_category_custom_fields($term_id) {
if (isset($_POST['custom_field'])) {
$custom_field_value = sanitize_text_field($_POST['custom_field']);
add_term_meta($term_id, 'custom_field', $custom_field_value, true);
}
}
add_action('created_category', 'save_category_custom_fields');
// Add custom field to category edit screen
function edit_category_custom_fields($tag) {
$term_id = $tag->term_id;
$custom_field_value = get_term_meta($term_id, 'custom_field', true); // Fetch existing value if any
?>
<tr class="form-field">
<th scope="row" valign="top">
<label for="custom_field"><?php _e('Custom Field'); ?></label>
</th>
<td>
<input type="text" name="custom_field" id="custom_field" value="<?php echo esc_attr($custom_field_value); ?>">
<p class="description"><?php _e('Enter custom field value here.'); ?></p>
</td>
</tr>
<?php
}
add_action('category_edit_form_fields', 'edit_category_custom_fields');
// Save custom field value when category is edited
function update_category_custom_fields($term_id) {
if (isset($_POST['custom_field'])) {
$custom_field_value = sanitize_text_field($_POST['custom_field']);
update_term_meta($term_id, 'custom_field', $custom_field_value);
}
}
add_action('edited_category', 'update_category_custom_fields');