Last active
November 17, 2018 21:05
-
-
Save igorveremsky/63692b1e4718849c3f93992bc7ad783e to your computer and use it in GitHub Desktop.
Extra fields for post category in WordPress
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?php | |
//add extra fields to category edit form callback function | |
function extra_category_fields( $tag ) { //check for existing featured ID | |
$t_id = $tag->term_id; | |
$cat_meta = get_option( "category_$t_id"); | |
?> | |
<tr class="form-field"> | |
<th scope="row" valign="top"><label for="cat_meta[custom_color]"><?php _e('Custom Color'); ?></label></th> | |
<td> | |
<input type="text" name="cat_meta[custom_color]" id="cat_meta[custom_color]" value="<?php echo $cat_meta['custom_color'] ? $cat_meta['custom_color'] : ''; ?>"><br /> | |
<span class="description"><?php _e('Custom color for category in HEX format'); ?></span> | |
</td> | |
</tr> | |
<?php | |
} | |
//add extra fields to category edit form hook | |
add_action ( 'edit_category_form_fields', 'extra_category_fields'); | |
// save extra category extra fields callback function | |
function save_extra_category_fileds( $term_id ) { | |
if ( isset( $_POST['cat_meta'] ) ) { | |
$t_id = $term_id; | |
$cat_meta = get_option( "category_$t_id"); | |
$cat_keys = array_keys($_POST['cat_meta']); | |
foreach ($cat_keys as $key){ | |
if (isset($_POST['cat_meta'][$key])){ | |
$cat_meta[$key] = $_POST['cat_meta'][$key]; | |
} | |
} | |
//save the option array | |
update_option( "category_$t_id", $cat_meta ); | |
} | |
} | |
// save extra category extra fields hook | |
add_action ( 'edited_category', 'save_extra_category_fileds'); |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?php | |
//first current category ID | |
$cat_id = CATEGORY_ID; | |
//then i get the data from the database | |
$cat_data = get_option("category_$cat_id"); | |
//and then i just display my category image if it exists | |
if ($cat_custom_color = $cat_data['custom_color']){ | |
print_r($cat_custom_color); // returns custom color for category | |
} | |
print_r($cat_data); // returns asssociate array with all custom fields for category |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment