Adding Custom Meta Fields to Taxonomies in WordPress

Adding Custom Meta Fields to Taxonomies in WordPress
392 Views

For add Custom Meta Field in taxonomy use following code in your current themes functions.php file.

<?php
// Add term page
add_action( 'category_add_form_fields', 'cxc_taxonomy_add_new_meta_field', 10, 2 );

function cxc_taxonomy_add_new_meta_field() {
	// this will add the custom meta field to the add new term page
	?>
	<div class="form-field">
		<label for="custom_term_meta"><?php _e( 'Custom meta field', 'cxc-codexcoach' ); ?></label>
		<input type="text" name="custom_term_meta" id="custom_term_meta" value="">
		<p class="description"><?php _e( 'Enter a value for this field','cxc-codexcoach' ); ?></p>
	</div>
	<?php
}
?>

Edit with term page

<?php
// Edit term page
add_action( 'category_edit_form_fields', 'cxc_taxonomy_edit_meta_field', 10, 2 );

function cxc_taxonomy_edit_meta_field( $term ) {

	// put the term ID into a variable
	$term_id = $term->term_id;

	// retrieve the existing value(s) for this meta field. This returns an array
	$term_meta = get_term_meta( $term_id, 'custom_term_meta', true ); ?>
	<tr class="form-field">
		<th scope="row" valign="top"><label for="custom_term_meta]"><?php _e( 'Example meta field', 'cxc-codexcoach' ); ?></label></th>
		<td>
			<input type="text" name="custom_term_meta" id="custom_term_meta" value="<?php echo ( !empty($term_meta) ) ? $term_meta  : ''; ?>">
			<p class="description"><?php _e( 'Enter a value for this field','cxc-codexcoach' ); ?></p>
		</td>
	</tr>
	<?php
}
?>

Save extra taxonomy fields

<?php
// Save extra taxonomy fields callback function.
add_action( 'edited_category', 'cxc_save_taxonomy_custom_meta', 10, 2 );  
add_action( 'create_category', 'cxc_save_taxonomy_custom_meta', 10, 2 );

function cxc_save_taxonomy_custom_meta( $term_id ) {
	if ( isset( $_POST['custom_term_meta'] ) && !empty( $_POST['custom_term_meta'] ) ) {
		update_term_meta( $term_id, 'custom_term_meta', $_POST['custom_term_meta'] );
	}
} 
?>

Use below code to show metabox values from anywhere

<?php
$terms = get_the_terms( get_the_ID() , 'category' ); // Here Specify your taxonomy name
if( !empty( $terms ) ){ ?>
	<ul>
		<?php foreach ( $terms as $term ) {
			$custom_term_meta = get_term_meta($term->term_id, 'custom_term_meta', true);
			if(!empty($custom_term_meta)) { ?>
				<li><?php echo $custom_term_meta; ?>
			<?php }  } ?>
	</ul>
<?php } ?>	

Was this article helpful?
YesNo

Leave a comment

Your email address will not be published.