To add a custom field for the WordPress category admin, you need to use two functions: add_category_form_fields and edit_category_form_fields. Additionally, you'll need to use the created_category and edited_category hooks to save the custom field data.\n\nHere's an example code snippet that demonstrates how to add a custom field for the category admin:\n\nphp\n// Add custom field to category add form\nfunction add_category_custom_field() {\n ?>\n <div class="form-field">\n <label for="custom_field"><?php _e('Custom Field', 'textdomain'); ?></label>\n <input type="text" name="custom_field" id="custom_field" value="" />\n <p class="description"><?php _e('Enter a value for the custom field', 'textdomain'); ?></p>\n </div>\n <?php\n}\nadd_action('category_add_form_fields', 'add_category_custom_field', 10, 2);\n\n// Add custom field to category edit form\nfunction edit_category_custom_field($tag) {\n $custom_field = get_term_meta($tag->term_id, 'custom_field', true);\n ?>\n <tr class="form-field">\n <th scope="row" valign="top"><label for="custom_field"><?php _e('Custom Field', 'textdomain'); ?></label></th>\n <td>\n <input type="text" name="custom_field" id="custom_field" value="<?php echo esc_attr($custom_field); ?>" />\n <p class="description"><?php _e('Enter a value for the custom field', 'textdomain'); ?></p>\n </td>\n </tr>\n <?php\n}\nadd_action('category_edit_form_fields', 'edit_category_custom_field', 10, 2);\n\n// Save custom field data\nfunction save_category_custom_field($term_id) {\n if (isset($_POST['custom_field'])) {\n update_term_meta($term_id, 'custom_field', sanitize_text_field($_POST['custom_field']));\n }\n}\nadd_action('created_category', 'save_category_custom_field', 10, 2);\nadd_action('edited_category', 'save_category_custom_field', 10, 2);\n\n\nMake sure to replace 'textdomain' with your own text domain.\n\nAfter adding this code to your theme's functions.php file or a custom plugin, you should see the custom field on the category add/edit pages in the WordPress admin. The custom field data will be saved when you create or update a category.


原文地址: https://www.cveoy.top/t/topic/nepA 著作权归作者所有。请勿转载和采集!

免费AI点我,无需注册和登录