Skip to content

Instantly share code, notes, and snippets.

@igorbenic
Last active July 7, 2025 10:26
Show Gist options
  • Save igorbenic/2b4e3e929629bba7a9fa48458e57781a to your computer and use it in GitHub Desktop.
Save igorbenic/2b4e3e929629bba7a9fa48458e57781a to your computer and use it in GitHub Desktop.
How to Add Custom Fields to WordPress Taxonomies | http://www.ibenic.com/custom-fields-wordpress-taxonomies
<?php
do_action( "{$taxonomy}_add_form_fields", string $taxonomy );
<?php
/**
* Adding Image Field
* @return void
*/
function category_add_image( $term ) {
?>
<div class="form-field">
<label for="taxImage"><?php _e( 'Image', 'yourtextdomain' ); ?></label>
<input type="text" name="taxImage" id="taxImage" value="">
</div>
<?php
}
add_action( 'category_add_form_fields', 'category_add_image', 10, 2 );
<?php
do_action( "{$taxonomy}_edit_form_fields", object $tag, string $taxonomy );
<?php
/**
* Edit Image Field
* @return void
*/
function category_edit_image( $term ) {
// put the term ID into a variable
$t_id = $term->term_id;
$term_image = get_term_meta( $t_id, 'image', true );
?>
<tr class="form-field">
<th><label for="taxImage"><?php _e( 'Image', 'yourtextdomain' ); ?></label></th>
<td>
<input type="text" name="taxImage" id="taxImage" value="<?php echo esc_attr( $term_image ) ? esc_attr( $term_image ) : ''; ?>">
</td>
</tr>
<?php
}
add_action( 'category_edit_form_fields', 'category_edit_image', 10 );
<?php
do_action( "edited_{$taxonomy}", int $term_id, int $tt_id );
do_action( "created_{$taxonomy}", int $term_id, int $tt_id );
<?php
/**
* Saving Image
*/
function category_save_image( $term_id ) {
if ( isset( $_POST['taxImage'] ) ) {
$term_image = $_POST['taxImage'];
if( $term_image ) {
update_term_meta( $term_id, 'image', $term_image );
}
}
}
add_action( 'edited_category', 'category_save_image' );
add_action( 'create_category', 'category_save_image' );
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment