Skip to content

Instantly share code, notes, and snippets.

@michaelschofield
Last active June 20, 2018 20:58
Show Gist options
  • Save michaelschofield/b20b0daa43b0ce554b8b to your computer and use it in GitHub Desktop.
Save michaelschofield/b20b0daa43b0ce554b8b to your computer and use it in GitHub Desktop.
Add Custom Meta Field to Custom Taxonomy
<?php
// Using the custom taxonomy "series" as an example
// Add term page
function lx_add_meta_field_to_taxonomy() {
?>
<div class="form-field">
<label for="term_meta[custom_term_meta]"><?php _e( 'Example meta field', 'yourtheme' ); ?></label>
<input type="text" name="term_meta[custom_term_meta]" id="term_meta[custom_term_meta]" value="">
<p class="description"><?php _e( 'Enter a value for this field','yourtheme' ); ?></p>
</div>
<?php
}
add_action( 'series_add_form_fields', 'lx_add_meta_field_to_taxonomy', 10, 2 );
// Edit term page
function lx_taxonomy_edit_meta_field($term) {
// put the term ID into a variable
$t_id = $term->term_id;
// retrieve the existing value(s) for this meta field. This returns an array
$term_meta = get_option( "taxonomy_$t_id" ); ?>
<tr class="form-field">
<th scope="row" valign="top"><label for="term_meta[custom_term_meta]"><?php _e( 'Example meta field', 'yourtheme' ); ?></label></th>
<td>
<input type="text" name="term_meta[custom_term_meta]" id="term_meta[custom_term_meta]" value="<?php echo esc_attr( $term_meta['custom_term_meta'] ) ? esc_attr( $term_meta['custom_term_meta'] ) : ''; ?>">
<p class="description"><?php _e( 'Enter a value for this field','yourtheme' ); ?></p>
</td>
</tr>
<?php
}
add_action( 'series_edit_form_fields', 'lx_taxonomy_edit_meta_field', 10, 2 );
// Save extra taxonomy fields callback function.
function lx_save_taxonomy_custom_meta( $term_id ) {
if ( isset( $_POST['term_meta'] ) ) {
$t_id = $term_id;
$term_meta = get_option( "taxonomy_$t_id" );
$cat_keys = array_keys( $_POST['term_meta'] );
foreach ( $cat_keys as $key ) {
if ( isset ( $_POST['term_meta'][$key] ) ) {
$term_meta[$key] = $_POST['term_meta'][$key];
}
}
// Save the option array.
update_option( "taxonomy_$t_id", $term_meta );
}
}
add_action( 'edited_series', 'lx_save_taxonomy_custom_meta', 10, 2 );
add_action( 'create_series', 'lx_save_taxonomy_custom_meta', 10, 2 );
?>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment