I need a Custom field for background color for every category in WordPress, anyone have any idea?
Thanks in Advance 🙂
Advertisement
Answer
Put below code in functions.php file of your theme for admin side.
<?php add_action('category_add_form_fields', 'add_background_color_field'); add_action('category_edit_form_fields', 'edit_background_color_field'); add_action('edit_term', 'save_background_color_field'); add_action('create_term', 'save_background_color_field'); function add_background_color_field() { echo '<div class="form-field"> <label for="category_background_color">Background Color</label> <input type="text" name="category_background_color" id="category_background_color" value="" /> <p class="description">Category Background Color.</p> </div>'; } function save_background_color_field($term_id) { if(isset($_POST['category_background_color'])) update_option('cat_background_color'.$term_id, $_POST['category_background_color']); } function edit_background_color_field($category) { $background_color = get_option('cat_background_color'.$category->term_id); echo '<tr class="form-field"> <th scope="row" valign="top"><label for="category_background_color">Background Color</label></th> <td> <input type="text" name="category_background_color" id="category_background_color" value="'.$background_color.'" /> <p class="description">Category Background Color.</p> </td> </tr>'; } ?>
Use below code for front end.
<?php $cat_id = get_query_var('cat'); $background_color = get_option('cat_background_color'.$cat_id); ?>
Use $background_color variable value wherever you want to use category background color in your archive.php or category.php file.