要实现这一点,请执行以下简单步骤:
添加颜色字段以使用挂钩添加/编辑类别屏幕category_add_form_fields 和category_edit_form_fields
add_action(\'category_add_form_fields\', \'my_category_fields\', 10, 2);
add_action(\'category_edit_form_fields\', \'my_category_fields\', 10, 2);
function my_category_fields($term) {
$cat_color = get_term_meta($term->term_id, \'cat_color\', true);
if($cat_color == \'\') $cat_color = \'#000000\'; // Default black color
?>
<tr class="form-field">
<th valign="top" scope="row"><label for="cat_color"><?php _e(\'Color code\'); ?></label></th>
<td>
<input type="color" size="40" value="<?php echo esc_attr($cat_color); ?>" id="cat_color" name="cat_color"><br/>
<span class="description"><?php _e(\'Please select a color\'); ?></span>
</td>
</tr>
<?php
}
使用挂钩保存从添加/编辑类别屏幕提交的颜色字段
edited_category 和
create_categoryadd_action(\'edited_category\', \'save_my_category_fields\', 10, 2);
add_action(\'create_category\', \'save_my_category_fields\', 10, 2);
function save_my_category_fields($term_id) {
if (!isset($_POST[\'cat_color\'])) {
return;
}
update_term_meta($term_id, \'cat_color\', sanitize_text_field($_POST[\'cat_color\']));
}
最后使用保存的颜色
get_term_meta()get_term_meta($term_id, \'cat_color\', true); // Replace $term_id with your own
例如,
<?php
$categories = wp_get_post_categories( $post_id );
foreach($categories as $category) {
$color = get_term_meta($category->term_id, \'cat_color\', true);
?>
<li>
<span class="label" style="background: <?php echo $color ; ?>">
<a href="<?php echo get_category_link( $category->term_id ); ?>" >
<?php echo $category->name ; ?>
</a>
</span>
</li>
<?php
}
?>
我希望这对你有帮助!