Custom color for each category name

To achieve this Follow these easy step:

  1. Add field for color To Add/Edit category Screen using hooks category_add_form_fields and 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
    }
    
  2. Save field for color submitted from Add/Edit category Screen using hooks edited_category and create_category

    add_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']));
    
    }
    
  3. Finally use the saved color by using get_term_meta()

    get_term_meta($term_id, 'cat_color', true);   // Replace $term_id with your own
    

For example,

<?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="https://wordpress.stackexchange.com/questions/330293/<?php echo get_category_link( $category->term_id ); ?>" >
             <?php echo $category->name ; ?>
         </a>
      </span>
    </li>
<?php 
   }
 ?>

I hope this will help you!

Leave a Comment