Use Nette Forms to Simplify WordPress Taxonomy Custom Field UIs

WordPress 4.3 added support for taxonomy term meta, which made custom fields for categories and other taxonomies much more practical. The missing piece is that WordPress does not provide a particularly elegant UI layer for those fields. The official examples work, but they build the form with a lot of mixed PHP and HTML, which becomes difficult to maintain.

One useful alternative is to build the taxonomy field UI with Nette Forms. It saves time, keeps the form logic cleaner, and makes the code easier to maintain.

Load Nette Forms and build the term edit form

Nette Forms supports Composer autoloading, so once the library is installed you can include the autoloader and start building the form. The basic idea is to read the saved term meta first and use it as the default value while rendering the edit screen.

require_once dirname(__FILE__) . '/../vendor/autoload.php';

use NetteFormsForm;

add_action('product_cat_edit_form_fields', 'edit_feature_group_field', 10, 2);

function edit_feature_group_field($term, $taxonomy) {
    $hlf_url = get_term_meta($term->term_id, 'hlf_url', true);
    $hlf_text = get_term_meta($term->term_id, 'hlf_text', true);
    $show_in_home = get_term_meta($term->term_id, 'show_in_home', true);

    $form = new Form;
    $form->addText('hlf_url', 'Link URL')
         ->setDefaultValue($hlf_url);
    $form->addText('hlf_text', 'Link Text')
         ->setDefaultValue($hlf_text);
    $form->addCheckbox('show_in_home', 'Show on home page')
         ->setDefaultValue($show_in_home);

    echo '<tr class="form-field"><td colspan="2">';
    echo $form;
    echo '</td></tr>';
}

Save the submitted custom field data

Rendering the form is only half of the job. You also need to save the submitted values. That part is simple: read the submitted values and store them with the term meta update functions.

add_action('edited_product_cat', 'update_feature_meta', 10, 2);

function update_feature_meta($term_id, $tt_id) {
    $hlf_url = $_POST['hlf_url'];
    $hlf_text = $_POST['hlf_text'];
    $show_in_home = sanitize_title($_POST['show_in_home']);

    update_term_meta($term_id, 'hlf_url', $hlf_url);
    update_term_meta($term_id, 'hlf_text', $hlf_text);
    update_term_meta($term_id, 'show_in_home', $show_in_home);
}

If you prefer, you can also preprocess the submitted values before saving them, or write them into a custom table instead of using the default term meta table. The same pattern can be adapted for post meta, user meta, and settings screens as well.

Related Posts

Leave a Reply

Your email address will not be published. Required fields are marked *