18

Now that WordPress 4.4 is out, we can start using the new awesome term meta functions!

Still, there seems to be no simple tutorial on how to add a basic text field to a Taxonomy. I tried to adapt this awesome tutorial by Justin Tadlock to my needs, removing all the code relating to the color picker and replacing it with a simple text input field... but it ain't working.

Could someone provide a bare-bones working code sample? Without data validation, nonces, color pickers... just a minimal text box, added to the Add taxonomy / Edit taxonomy page.

Update: In the meantime, I made a few variations of this code snippet:

Add term meta field to Category:
https://gist.github.com/ms-studio/543a0f7dd8ac05ccf037

Add term meta field to Post Tag:
https://gist.github.com/ms-studio/2d78ad3839e05ece2e48

Add term meta field to Custom Taxonomy:
https://gist.github.com/ms-studio/fc21fd5720f5bbdfaddc

Add several term meta fields to Custom Taxonomy:
https://gist.github.com/ms-studio/aeae733f5fd9fc524bbc

  • Please post your current code snippet and how it fails. – birgire Dec 14 '15 at 1:42
  • @birgire sorry for not posting my original code, but it was already too messed up, and I would rather start from a clean example. – Manu Dec 14 '15 at 20:56
13

This will add a field called 'TERM META TEXT' to your categories. I did take out the nonce but I really think it should go back in. Also, it's just better to have some sanitization vs. none. This example includes javascript and CSS hooks which you may or may not need but you can quickly see how all the parts go together.

Enjoy!

// REGISTER TERM META

add_action( 'init', '___register_term_meta_text' );

function ___register_term_meta_text() {

    register_meta( 'term', '__term_meta_text', '___sanitize_term_meta_text' );
}

// SANITIZE DATA

function ___sanitize_term_meta_text ( $value ) {
    return sanitize_text_field ($value);
}

// GETTER (will be sanitized)

function ___get_term_meta_text( $term_id ) {
  $value = get_term_meta( $term_id, '__term_meta_text', true );
  $value = ___sanitize_term_meta_text( $value );
  return $value;
}

// ADD FIELD TO CATEGORY TERM PAGE

add_action( 'category_add_form_fields', '___add_form_field_term_meta_text' );

function ___add_form_field_term_meta_text() { ?>
    <?php wp_nonce_field( basename( __FILE__ ), 'term_meta_text_nonce' ); ?>
    <div class="form-field term-meta-text-wrap">
        <label for="term-meta-text"><?php _e( 'TERM META TEXT', 'text_domain' ); ?></label>
        <input type="text" name="term_meta_text" id="term-meta-text" value="" class="term-meta-text-field" />
    </div>
<?php }


// ADD FIELD TO CATEGORY EDIT PAGE

add_action( 'category_edit_form_fields', '___edit_form_field_term_meta_text' );

function ___edit_form_field_term_meta_text( $term ) {

    $value  = ___get_term_meta_text( $term->term_id );

    if ( ! $value )
        $value = ""; ?>

    <tr class="form-field term-meta-text-wrap">
        <th scope="row"><label for="term-meta-text"><?php _e( 'TERM META TEXT', 'text_domain' ); ?></label></th>
        <td>
            <?php wp_nonce_field( basename( __FILE__ ), 'term_meta_text_nonce' ); ?>
            <input type="text" name="term_meta_text" id="term-meta-text" value="<?php echo esc_attr( $value ); ?>" class="term-meta-text-field"  />
        </td>
    </tr>
<?php }


// SAVE TERM META (on term edit & create)

add_action( 'edit_category',   '___save_term_meta_text' );
add_action( 'create_category', '___save_term_meta_text' );

function ___save_term_meta_text( $term_id ) {

    // verify the nonce --- remove if you don't care
    if ( ! isset( $_POST['term_meta_text_nonce'] ) || ! wp_verify_nonce( $_POST['term_meta_text_nonce'], basename( __FILE__ ) ) )
        return;

    $old_value  = ___get_term_meta_text( $term_id );
    $new_value = isset( $_POST['term_meta_text'] ) ? ___sanitize_term_meta_text ( $_POST['term_meta_text'] ) : '';


    if ( $old_value && '' === $new_value )
        delete_term_meta( $term_id, '__term_meta_text' );

    else if ( $old_value !== $new_value )
        update_term_meta( $term_id, '__term_meta_text', $new_value );
}

// MODIFY COLUMNS (add our meta to the list)

add_filter( 'manage_edit-category_columns', '___edit_term_columns' );

function ___edit_term_columns( $columns ) {

    $columns['__term_meta_text'] = __( 'TERM META TEXT', 'text_domain' );

    return $columns;
}

// RENDER COLUMNS (render the meta data on a column)

add_filter( 'manage_category_custom_column', '___manage_term_custom_column', 10, 3 );

function ___manage_term_custom_column( $out, $column, $term_id ) {

    if ( '__term_meta_text' === $column ) {

        $value  = ___get_term_meta_text( $term_id );

        if ( ! $value )
            $value = '';

        $out = sprintf( '<span class="term-meta-text-block" style="" >%s</div>', esc_attr( $value ) );
    }

    return $out;
}

// ADD JAVASCRIPT & STYLES TO COLUMNS

add_action( 'admin_enqueue_scripts', '___admin_enqueue_scripts' );

function ___admin_enqueue_scripts( $hook_suffix ) {

    if ( 'edit-tags.php' !== $hook_suffix || 'category' !== get_current_screen()->taxonomy )
        return;

    // ADD YOUR SUPPORTING CSS / JS FILES HERE
    // wp_enqueue_style( 'wp-color-picker' );
    // wp_enqueue_script( 'wp-color-picker' );

    add_action( 'admin_head',   '___meta_term_text_print_styles' );
    add_action( 'admin_footer', '___meta_term_text_print_scripts' );
}

// PRINT OUR CUSTOM STYLES

function ___meta_term_text_print_styles() { ?>

    <style type="text/css">
        .column-__term_meta_text { background-color:rgb(249, 249, 249); border: 1px solid lightgray;}
        .column-__term_meta_text .term-meta-text-block { display: inline-block; color:darkturquoise; }
    </style>
<?php }

// PRINT OUR CUSTOM SCRIPTS

function ___meta_term_text_print_scripts() { ?>

    <script type="text/javascript">
        jQuery( document ).ready( function( $ ) {
             $input_field = $( '.term-meta-text-field' );
             // console.log($input_field); // your input field
        } );
    </script>
<?php }
  • Thanks a lot, this is really helpful! But when applying the code as-is, I encounter one issue : the TERM META TEXT field is updated when a term is modified, but is not saved when a term is created. – Manu Dec 14 '15 at 17:54
  • I tried on another test site, and saw the same behavior – everything working fine, except that upon term creation, the meta text wasn’t saved. I disabled the nonce verification inside ___save_term_meta_text( $term_id ) ... and this fixed the problem, the meta text is now saved when creating a new term! I'm accepting therefore your answer, as it provides exactly what I need to get started. – Manu Dec 14 '15 at 20:53
  • 1
    I just understood what caused the issue: the nonce wasn't being defined in the ___add_form_field_term_meta_text() function. After adding it, all works as expected. – Manu Dec 14 '15 at 21:04
  • 1
    No need to pollute with additional nonces since WP has already placed some. Just do check_admin_referer( 'add-tag', '_wpnonce_add-tag' ); and check_admin_referer( 'update-tag_' . (int) $_POST['tag_ID'] ) in 'edit_category' and 'category_category' actions. – Zlatev Oct 9 '16 at 13:55
  • It is worth noting that in your ___register_term_meta_text() function, the third parameter has been deprecated and replaced with an array instead. You would have to use something like: $args = array( 'type' => 'string', 'description' => 'A text field', 'single' => 'false', 'sanitize_callback' => '___sanitize_term_meta_weare_product', 'auth_callback' => null, 'show_in_rest' => false, ); register_meta( 'term', '__term_meta_text', $args ); – Frits Apr 19 '17 at 11:46

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.