Using WordPress ‘edit_category_form’ PHP action

The edit_category_form WordPress PHP action fires at the end of the Edit Category form, enabling you to modify the form or add custom fields.

Usage

add_action('edit_category_form', 'your_custom_function');
function your_custom_function($arg) {
  // your custom code here
}

Parameters

  • $arg (object) – arguments cast to an object.

More information

See WordPress Developer Resources: edit_category_form

Examples

Add a custom field to the Edit Category form

This example adds a custom field to the Edit Category form.

add_action('edit_category_form', 'add_custom_field_to_edit_category_form');
function add_custom_field_to_edit_category_form($category) {
  // Retrieve the custom field value if it exists
  $custom_field_value = get_term_meta($category->term_id, 'custom_field', true);

  // Display the custom field input
  echo '<tr class="form-field">
          <th scope="row"><label for="custom_field">Custom Field</label></th>
          <td>
            <input type="text" name="custom_field" id="custom_field" value="' . esc_attr($custom_field_value) . '">
            <p class="description">Enter a value for the custom field.</p>
          </td>
        </tr>';
}

Save custom field value in Edit Category form

This example saves the custom field value from the Edit Category form.

add_action('edited_category', 'save_custom_field_value', 10, 2);
function save_custom_field_value($term_id, $taxonomy_id) {
  if (isset($_POST['custom_field'])) {
    update_term_meta($term_id, 'custom_field', sanitize_text_field($_POST['custom_field']));
  }
}

Add custom CSS to the Edit Category form

This example adds custom CSS to the Edit Category form.

add_action('edit_category_form', 'add_custom_css_to_edit_category_form');
function add_custom_css_to_edit_category_form() {
  echo '<style>
          .form-field label { color: red; }
        </style>';
}

Add a custom JavaScript event to the Edit Category form

This example adds a custom JavaScript event to the Edit Category form.

add_action('edit_category_form', 'add_custom_js_event_to_edit_category_form');
function add_custom_js_event_to_edit_category_form() {
  echo '<script>
          document.getElementById("submit").addEventListener("click", function() {
            alert("Form submitted!");
          });
        </script>';
}

Validate custom field value in Edit Category form

This example validates the custom field value before submitting the Edit Category form.

add_action('edit_category_form', 'validate_custom_field_value');
function validate_custom_field_value() {
  echo '<script>
          document.getElementById("submit").addEventListener("click", function(event) {
            var customField = document.getElementById("custom_field").value;
            if (customField === "") {
              event.preventDefault();
              alert("Please enter a value for the custom field.");
            }
          });
        </script>';
}