Navigation Menu

Skip to content

Instantly share code, notes, and snippets.

@davekelly
Created May 22, 2012 15:14
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save davekelly/2769687 to your computer and use it in GitHub Desktop.
Save davekelly/2769687 to your computer and use it in GitHub Desktop.
Add a custom field to a Custom Taxonomy (WordPress)
<?php
/**
* Used to attach a gallery shortcode to a custom taxonomy (but has more general uses)
*
* Uses code from:
* @link http://sabramedia.com/blog/how-to-add-custom-fields-to-custom-taxonomies
*/
// in functions.php / custom post setup file...
// A callback function to add a custom field to our "tf_foodmenu" taxonomy
function tf_menu_taxonomy_custom_fields($tag) {
// Check for existing taxonomy meta for the term you're editing
$t_id = $tag->term_id; // Get the ID of the term you're editing
$term_meta = get_option( "taxonomy_term_$t_id" ); // Do the check
?>
<tr class="form-field">
<th scope="row" valign="top">
<label for="tax_gallery_code"><?php _e('Image Gallery Shortcode (optional)'); ?></label>
</th>
<td>
<input type="text" name="term_meta[tax_gallery_code]" id="term_meta[tax_gallery_code]" size="25" style="width:60%;" value="<?php echo $term_meta['tax_gallery_code'] ? $term_meta['tax_gallery_code'] : ''; ?>"><br />
<span class="description"><?php _e('Image Gallery Shortcode (optional)'); ?></span>
</td>
</tr>
<?php
}
// A callback function to save our extra taxonomy field(s)
function save_taxonomy_custom_fields( $term_id ) {
if ( isset( $_POST['term_meta'] ) ) {
$t_id = $term_id;
$term_meta = get_option( "taxonomy_term_$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_term_$t_id", $term_meta );
}
}
// Add the fields to the "presenters" taxonomy, using our callback function
add_action( 'tf_foodmenucat_edit_form_fields', 'tf_menu_taxonomy_custom_fields', 10, 2 );
// Save the changes made on the "presenters" taxonomy, using our callback function
add_action( 'edited_tf_foodmenucat', 'save_taxonomy_custom_fields', 10, 2 );
?>
<?php
// -------------------------------------
// ** In Template **
//
// Grab & echo the output
// (in this case it's a shortcode, so process it in the template)
// -------------------------------------
// Taxonomies can have a gallery shortcode for sidebar images
$taxCustomFields = get_option( "taxonomy_term_$term->term_id" );
$taxonomyGalleryShortCode = isset($taxCustomFields['tax_gallery_code']) ? $taxCustomFields['tax_gallery_code'] : false;
?>
<?php if( $taxonomyGalleryShortCode ): ?>
<?php echo do_shortcode( $taxonomyGalleryShortCode); ?>
<?php endif; ?>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment