Skip to content

Instantly share code, notes, and snippets.

@shizhua
Last active July 19, 2022 03:23
Show Gist options
  • Save shizhua/4f5f7cf4f353a1bcac5b to your computer and use it in GitHub Desktop.
Save shizhua/4f5f7cf4f353a1bcac5b to your computer and use it in GitHub Desktop.
Add custom field to Category and taxonomies
<?php
// Add the field to the Add New Category page
add_action( 'category_add_form_fields', 'pt_taxonomy_add_new_meta_field', 10, 2 );
function pt_taxonomy_add_new_meta_field() {
// this will add the custom meta field to the add new term page
?>
<div class="form-field">
<label for="term_meta[cat_icon]"><?php _e( 'Font Awesome Icons', 'pt' ); ?></label>
<input type="text" name="term_meta[cat_icon]" id="term_meta[cat_icon]" value="">
<p class="description"><?php printf(__( 'Choose your category icon from <a href="%s" target="_blank">Font Awesome Icons</a>. For example: <b>fa-wordpress</b>','pt' ), 'http://fontawesome.io/icons/'); ?></p>
</div>
<?php
}
<?php
// Add the field to the Edit Category page
add_action( 'category_edit_form_fields', 'pt_taxonomy_edit_meta_field', 10, 2 );
function pt_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[cat_icon]"><?php _e( 'Font Awesome Icons', 'pt' ); ?></label></th>
<td>
<input type="text" name="term_meta[cat_icon]" id="term_meta[cat_icon]" value="<?php echo esc_attr( $term_meta['cat_icon'] ) ? esc_attr( $term_meta['cat_icon'] ) : ''; ?>">
<p class="description"><?php printf(__( 'Choose your category icon from <a href="%s" target="_blank">Font Awesome Icons</a>. For example: <b>fa-wordpress</b>','pt' ), 'http://fontawesome.io/icons/'); ?></p>
</td>
</tr>
<?php
}
<?php
$cat = get_the_category();
$cat_id = $cat[0]->term_id;
$cat_data = get_option("taxonomy_$cat_id");?>
<a href="<?php echo get_category_link($cat[0]->term_id); ?>">
<?php if (isset($cat_data['cat_icon'])){
echo '<i class="fa '.$cat_data['cat_icon'].'"></i>';
}
?>
<?php echo $cat[0]->cat_name; ?>
</a>
<?php
// Save extra taxonomy fields callback function.
add_action( 'edited_category', 'pt_save_taxonomy_custom_meta', 10, 2 );
add_action( 'create_category', 'pt_save_taxonomy_custom_meta', 10, 2 );
function pt_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 );
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment