要将自定义字段添加到自定义分类,请将以下代码添加到主题的functions.php:
// A callback function to add a custom field to our "presenters" taxonomy
function presenters_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="presenter_id"><?php _e('WordPress User ID'); ?></label>
</th>
<td>
<input type="text" name="term_meta[presenter_id]" id="term_meta[presenter_id]" size="25" style="width:60%;" value="<?php echo $term_meta['presenter_id'] ? $term_meta['presenter_id'] : ''; ?>"><br />
<span class="description"><?php _e('The Presenter\'s WordPress User ID'); ?></span>
</td>
</tr>
<?php
}
接下来,我们将创建一个回调函数,用于保存我们的自定义字段。将以下代码添加到主题的functions.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 );
}
}
上面的代码将“按原样”用于一个或多个自定义分类法,无需更改。
现在让我们将这些回调函数关联到自定义分类的“编辑”屏幕。为此,我们将使用可用于我们创建的每个自定义分类的两个 WordPress 操作挂钩。将以下代码添加到主题的functions.php:
// Add the fields to the "presenters" taxonomy, using our callback function
add_action( 'presenters_edit_form_fields', 'presenters_taxonomy_custom_fields', 10, 2 );
// Save the changes made on the "presenters" taxonomy, using our callback function
add_action( 'edited_presenters', 'save_taxonomy_custom_fields', 10, 2 );
要访问添加到自定义分类中的自定义字段,请在顶部的 PHP 块中的自定义分类模板(例如 taxonomy-presenters.php)中添加以下代码:
// Get the custom fields based on the $presenter term ID
$presenter_custom_fields = get_option( "taxonomy_term_$presenter->term_id" );
// Return the value for the "presenter_id" custom field
$presenter_data = get_userdata( $presenter_custom_fields[presenter_id] ); // Get their data
要使此示例正常工作,请确保您已在自定义字段中为您正在使用的术语保存了一个值。
<?php
echo '<pre>';
print_r( $presenter_custom_fields );
echo '</pre>';
?>