Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Star 7 You must be signed in to star a gist
  • Fork 4 You must be signed in to fork a gist
  • Save fdaciuk/6207824 to your computer and use it in GitHub Desktop.
Save fdaciuk/6207824 to your computer and use it in GitHub Desktop.
Adicionar novo campo (custom field) a uma taxonomia no WordPress (Incluir esse código no functions.php)Nas action_hooks, no lugar de "category" é só incluir o slug da sua taxonomia :)
<?php
// Add term page
function taxonomy_add_new_meta_field() {
// this will add the custom meta field to the add new term page
echo '
<div class="form-field">
<label for="term_meta[custom_term_meta]">Example meta field</label>
<input type="text" name="term_meta[custom_term_meta]" id="term_meta[custom_term_meta]" value="">
<p class="description">Enter a value for this field</p>
</div>
';
}
add_action( 'category_add_form_fields', 'taxonomy_add_new_meta_field', 10 );
// Edit term page
function 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}" );
$value = esc_attr( $term_meta['custom_term_meta'] ) ? esc_attr( $term_meta['custom_term_meta'] ) : '';
echo '
<tr class="form-field">
<th scope="row" valign="top"><label for="term_meta[custom_term_meta]">Example meta field</label></th>
<td>
<input type="text" name="term_meta[custom_term_meta]" id="term_meta[custom_term_meta]" value="' . $value . '">
<p class="description">Enter a value for this field</p>
</td>
</tr>
';
}
add_action( 'category_edit_form_fields', 'taxonomy_edit_meta_field', 10, 1 );
// Save extra taxonomy fields callback function.
function 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_category', 'save_taxonomy_custom_meta', 10, 1 );
add_action( 'create_category', 'save_taxonomy_custom_meta', 10, 1 );

Adicionar novo campo (custom field) a uma taxonomia (categoria, tag, etc) no WordPress

Incluir esse código no functions.php.

Nas action_hooks, no lugar de "category" é só incluir o slug da sua taxonomia :)

@horacioo
Copy link

horacioo commented Apr 8, 2015

e como eu faço para recuperar o valor desse campo em um template?

@fdaciuk
Copy link
Author

fdaciuk commented Nov 30, 2015

@mmaikeb
Copy link

mmaikeb commented Feb 19, 2019

Boa tarde.
Não consegui recuperar o valor pra exibir no front-end. Teria como ajudar?

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment