How to use taxonomy term meta in WordPress

WordPress 4.4 adds term_meta support and which is Awesome !

There has been a long way demand for this along the WordPress developer. Lets see what is this and how it is used.

What is `term meta` ?

Term meta is a piece of information attached to the taxonomy term(e.g. category). This piece of information can be anything which is tagged to taxonomy term.

For example movie is an taxonomy name for which you want to add a info named year of release to the movie term. Here year of release will be added as an term_meta.

How to add and use term meta ?

Now we will use the above example to show how to add add and use term meta.

The new functions introduced about term meta are:

Now we will add the Release Year to the taxomony term of movie.

The hook we’ll use are:

  • {$taxonomy}_add_form_fields – Hook for adding fields to the “new term” form.
  • {$taxonomy}_edit_form_fields – Hook for adding fields to the “edit term” form.

All the code will be added to themesfunctions.php if not specified.

This will add the Year field to the add form:

[php]add_action( ‘movie_add_form_fields’, ‘obs_add_movie_details’ );

function obs_add_movie_details() { ?>

<div class="form-field">
<label for="year">Year</label>
<input type="text" name="obs_movie_year" id="year" value="" />
</div>
<?php }[/php]

For the edit form:

[php]add_action( ‘movie_edit_form_fields’, ‘obs_edit_movie_details’ );

function obs_edit_movie_details( $term ) {

$year = get_term_meta( $term->term_id, ‘year’, true ); ?>

<tr class="form-field">
<th scope="row"><label for="year">Year</label></th>
<td>
<input type="text" name="obs_movie_year" id="year" value="<?php echo esc_attr( $year ); ?>" />
</td>
</tr>
<?php }[/php]

We have added the term meta form, now we need to save the meta. Two hooks we will use now:

  • create_{$taxonomy} – fires when creating the taxonomy
  • edit_{$taxonomy} – fires when editing the taxonomy

And the code is:

[php]

add_action( ‘edit_movie’, ‘obs_save_movie_details’ );
add_action( ‘create_movie’, ‘obs_save_movie_details’ );

function obs_save_movie_details( $term_id ) {

if ( ! isset( $_POST[‘obs_movie_year’] ) ){
return; }

if ( ” === $_POST[‘obs_movie_year’] ) { delete_term_meta( $term_id, ‘year’); }else{

update_term_meta( $term_id, ‘year’, $_POST[‘obs_movie_year’]);
}
}

[/php]

Now you have added the year term meta to your movie taxonomy term, you can use in in your site anywhere in template by using this:

get_term_meta($term_id, 'year', true);

Let’s try it!

You have learned how to use term_meta in your WordPress site, try using it. And let me know how you’re using it!

 

Spread the love