Bainternet WordPress Consultant
  • WordPress Services
  • Blog
    • Fancy Functions
    • ShortCodes
    • How To’s
  • Plugins
    • Custom Category Template
    • Author category
    • ShortCodes UI
    • Simple Gist Embed
    • Simple QR Code
    • WordPress Simple Instant Search Plugin
    • WordPress Advanced Code Editor
    • Simple Google +1 plugin
    • Simple TOC
    • User specific Content
    • User Ranks
      • Bainternet User Ranks v1.0
    • Post Creation Limits
      • Posts Creation Limits older versions
  • About Me
    • Donations
  • Contact me

how to – WordPress Category Extra Fields

Posted on Jan 28, 2011
Ohad Raz
55 Comments
How To
  • Share on Twitter
  • Share on Facebook
  • Share on Google+
  • Share on LinkedIn
how to - WordPress Category Extra Fields

Update
Check the new and easier way to add extra taxonomies fields

Recently i worked o a site that needed some modification to the category edit screen in order to display a different image for each category page (it’s also implemented in this site).
Now WordPress doesn’t have a category or tag meta data table in it’s database and i don’t know why but i never liked adding tables of my own. So I decided to work with the options table of WordPress. Before i start a side note: this could be done in the same way for categories, tags or any other custom taxonomies but this example will show how to on categories.
wordpress category extra fileds

Let’s get started

the first thing we need to do is add the extra fields to the category edit form using the hook edit_category_form_fields and we use a simple function that will print out the extra fields.

<?php
//add extra fields to category edit form hook
add_action ( 'edit_category_form_fields', 'extra_category_fields');
//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_Image_url"><?php _e('Category Image Url'); ?></label></th>
<td>
<input type="text" name="Cat_meta[img]" id="Cat_meta[img]" size="3" style="width:60%;" value="<?php echo $cat_meta['img'] ? $cat_meta['img'] : ''; ?>"><br />
            <span class="description"><?php _e('Image for category: use full url with http://'); ?></span>
        </td>
</tr>
<tr class="form-field">
<th scope="row" valign="top"><label for="extra1"><?php _e('extra field'); ?></label></th>
<td>
<input type="text" name="Cat_meta[extra1]" id="Cat_meta[extra1]" size="25" style="width:60%;" value="<?php echo $cat_meta['extra1'] ? $cat_meta['extra1'] : ''; ?>"><br />
            <span class="description"><?php _e('extra field'); ?></span>
        </td>
</tr>
<tr class="form-field">
<th scope="row" valign="top"><label for="extra2"><?php _e('extra field'); ?></label></th>
<td>
<input type="text" name="Cat_meta[extra2]" id="Cat_meta[extra2]" size="25" style="width:60%;" value="<?php echo $cat_meta['extra2'] ? $cat_meta['extra2'] : ''; ?>"><br />
            <span class="description"><?php _e('extra field'); ?></span>
        </td>
</tr>
<tr class="form-field">
<th scope="row" valign="top"><label for="extra3"><?php _e('extra field'); ?></label></th>
<td>
        	<textarea name="Cat_meta[extra3]" id="Cat_meta[extra3]" style="width:60%;"><?php echo $cat_meta['extra3'] ? $cat_meta['extra3'] : ''; ?></textarea><br />
            <span class="description"><?php _e('extra field'); ?></span>
        </td>
</tr>
<?php
}

As you can see i added 4 new fields and all of them are in an array Cat_meta[key] because that way we only create on row in the options table to save all of the category’s extra fields instead of a row for each field.
Next we need to save the extra fields in to the database once a user submits the category edit form and we do that using “edited_category” with a function that will run through each of the submitted fields and insert them to the database using the update_option function, like this:

<?php
// save extra category extra fields hook
add_action ( 'edited_category', 'save_extra_category_fileds');
   // 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 );
	}
}

From the code above you can see that all of the extra fields we’ve added are stored in the database’s options table with the name ‘category_ID’ , where ID is the id of the specific category we just edited and that means we can call this data in our plugins or theme files easily using the get_option function.

say for example my category id is 25 then my code will look like

<?php $cat_data = get_option('category_25'); ?>

As i stated in the beginning of this post i need to display a different image for each category, so in that case i added this few lines of code to my theme’s category.php right after the code that displays the category title:

<?php
//first get the current category ID
$cat_id = get_query_var('cat');
//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 (isset($cat_data['img'])){
echo '<div class="category_image"><img src="'.$cat_data['img'].'"></div>';
}

Nice and easy and we are all done.
next time I’ll show how we add extra fields to custom taxonomies which is pretty much the same but different hook.

Update
Check the new and easier way to add extra taxonomies fields

Incoming search terms:

  • wordpress category custom fields
  • how to add extra field Custom Contact Forms wordpress
  • how to add the category custom fields in category template
  • wordpress add images to categories
  • wordpress categories custom fields
  • wordpress custom category fiields
  • wordpress extrafields

Related posts:

  1. Contact me







55 Comments for how to – WordPress Category Extra Fields

Ivo Iliev  Feb 10, 2011

Thank You! Very useful indeed!
But, can we use this in the loop. Let’s say I neet to list all [img] data from all categories?

Reply

    bainternet  Feb 10, 2011

    @IVO Iliev – First thanks.
    You are not the only one who asked so i posted a quick how to
    list categories with images.

    Hope this helps.

    Reply

      Ivo Iliev  Feb 11, 2011

      Many, many 10x again!

      Just a little correction on 16-th line of the function:
      $cats[] = ”. $cat_image.’“‘ .$cat->name .’‘;

      Reply

        bainternet  Feb 11, 2011

        yeah i updated the code thanks

        Reply

    PBN  Apr 15, 2012

    Hi,
    very very very useful,
    tnx guy.

    Reply

Philip  Feb 19, 2011

To make it work in 3.1 i changed the “edit_category_form_fields” hook to “category_add_form_fields”,

thanks a lot for this bainternet!

Reply

    Robert Jakobson  Mar 04, 2011

    Philip and B. you both saved my day – awesome code for WordPress theme development!

    Reply

    Robert Jakobson  Mar 04, 2011

    P. that is not the way to go – with a change like this you loose the ability to add this fields to already created categories all this does is place the new fields in the “create new category” section, not useful at all, it is better to have it at “Edit this category” section, if you know what I mean.

    Also B. needs to change “fileds” to fields” in extra_category_fields

    Reply

      bainternet  Mar 05, 2011

      i fixed it , thanks

      Reply

Robert Jakobson  Mar 04, 2011

The code has something missing I am getting a Parse error: syntax error, unexpected ‘<' in line 5 of the first block of code.

Perhaps the matter lies in curly brakes, but it does not work right now.

Reply

    bainternet  Mar 05, 2011

    check if you got and extra

    tag at the beginning of that line and remove it.

    Reply

boris  Mar 06, 2011

Thanks for your work. Managed to have the extra fields but still don’t get how to add a category icon within the loop. My target is to have the specific category icon at the beginning of head title of an article…

Reply

    bainternet  Mar 06, 2011

    in your category.php or archive.php (depends on your theme) find something that looks like the_title(); and just before that add :

    //first get the current category ID
    $cat_id = get_query_var('cat');
    //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 (isset($cat_data['img'])){
        echo '<div class="category_image"><img src="'.$cat_data['img'].'"></div>';
    }

    if you want to create a list of categories with images then take a look at list categories with images

    Reply

Brad  Apr 15, 2011

Nice but how do we add the fields to the Add Categories screen, not just the edit screen?

Reply

    bainternet  Apr 16, 2011

    Sadly that is really not possible without editing core files since the whole thing is hard coded with no filter or action hooks.

    Reply

      Kyle Theisen  Nov 12, 2011

      I got it working by simply adding the following. Ohad, is there something I overlooked where this may cause other problems?

      add_action ( 'category_add_form_fields', 'extra_category_fields');
      add_action ( 'category_add_form_fields', 'extra_category_fields');

      Reply

        Ohad Raz  Nov 12, 2011

        @kyle:

        If i understand what you are asking then, No you are just fine since the hooks have changed a bit since i first posted this tutorial.

        Reply

          Kyle Theisen  Nov 12, 2011

          Good deal, just wanted to make sure I wasn’t missing anything. Thanks for the well written article.

          Patrick Tang  Nov 13, 2011

          Thanks for the splendid code, Ohad!

          A kind reminder, if the extra fields are added to “Add New Category” form, please make sure to add the following statement to the save function, so that the extra fields data are saved when a category is created

          add_action ( ‘created_category’, ‘save_extra_category_fileds’);

box  May 04, 2011

Thank you very much. Works like a charm.

Reply

Blackbam  May 12, 2011

Thank you, this was useful. The only good and fast tutorial I found on that issue, also needed it for category images and description.

Reply

    bainternet  May 17, 2011

    Glad you like it.

    Reply

Mark  May 17, 2011

Is there a way for the field values to repopulate. Meaning once you hit “Update” all the fields become blank…Shouldn’t they be saved and show up after updating? Maybe I’m doing something wrong?

Reply

    bainternet  May 18, 2011

    You are doing something wrong, because it should repopulate the fields once you update.
    also if you see any typo please let me know so i could correct.

    Reply

Mark  May 18, 2011

Yeah….my bad…there was a typo on my part. Thanks for this how to, it will come in really handy.

Reply

    bainternet  May 18, 2011

    :) Glad you figured it out.

    Reply

Mark  May 19, 2011

Has anyone tried to add a rich text editor to the additional fields? I used Rich Category Editor plugin….which works, except it has issues with html characters. Each time you save it the database adds slashes, which then get echoed back into the field. Every time it updates, it adds more slashes….I figured this out when my links weren’t working.

To fix this in the editor I changed this:
echo $cat_meta['rating'] ? $cat_meta['rating'] :

to this:
$term = $cat_meta['sidebarDetails'];
$term = stripslashes($term);
$term = html_entity_decode($term);

echo $term ? $term :

Then in your template files you have to stripslashes() and html_entity_decode() to the values that would have html:

//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 (isset($cat_data['extra-field'])){
$term = $cat_data['extra-field'];
$term = stripslashes($term);
$term = html_entity_decode($term);
echo $term;

}

Anyone else encounter this problem? If so, how did you go about fixing it?

Reply

Rafael  May 31, 2011

Nice Tutorial, Congratulations!

Reply

rob  Jul 05, 2011

Hi! How code line looks like wich I sould put into my category .php files to get this fields? Can you help me?

Reply

    bainternet  Jul 06, 2011

    @rob: Hummm, that’s what this post is about, try reading it again and more specifically the last part which has an example of how to use this fields values.

    Reply

Reed  Jul 07, 2011

Superlative code sir!

I’m sure it’s a simple matter, but I’m having trouble adding the image data into a category list. This is the loop I’m beginning with:

		 <?php
		  $categories=  get_categories('hide_empty=0&orderby=id&show_count=2&use_desc_for_title=0&child_of=62');
		  foreach ($categories as $cat){
			echo ";'.'<a>cat_ID).'"> ' . $cat->cat_name . '</a> ' . $cat->description.'';
		}
		 ?>
		

Any ideas? Thanks a great deal for any help you might be able to provide!

Reply

    bainternet  Jul 07, 2011

    this can’t be your code cause its wrong syntax and wont work, anyway take a look at the example at the end of the post.

    Reply

tom  Aug 12, 2011

Thanks for this :)

Eventually got exactly what I was after :)

Reply

Julian  Aug 22, 2011

Hello, thank you for this! it’s just what I was looking for, I had a problem while exporting my database the data stored in the img field was not exported and I had to insert it again, does anyone know why?!

bye!

Reply

    Ohad Raz  Aug 23, 2011

    @Julian: As you can read in the tutorial the data is saved in the options table, so any things could have gone wrong like the category ids have changed or you just haven’t imported the options table.

    Reply

      julian  Aug 23, 2011

      Hello! thank you for your answer… yeah I’ve just checked the options table in the imported wordpress database and the data was there, just like in my localhost… but when I go to edit category the field is empty and in the template, the custom category images doesn’t load

      Reply

Ohad Raz  Aug 24, 2011

@julian: I can’t really see whats the problem, the extra fields are saved as an array for each category in the options table, make sure that the category ids match in your template file,
if you want to send me the code you use in your custom category template so I’ll take a look, use the contact form and I’ll see what i can come up with.

Reply

Danny  Oct 14, 2011

just wondering is there a way to list all custom fields that isn’t empty into the frontend, I haven’t actually even tried it but I’m just wondering how you would do this?

Reply

    Ohad Raz  Oct 17, 2011

    Yep there is a way , take a look at the example at the end of the post.

    Reply

      danny  Oct 23, 2011

      I meant all the them like in list format carot,patato,tomato for example

      Reply

    Ohad Raz  Oct 23, 2011

    @Danny:

    Send me an email using the contact form in this site and I’ll try to help you.

    Reply

Alex Barber | Digital Artist | WordPress: Category custom fields  Nov 16, 2011

[...] http://en.bainternet.info/2011/wordpress-category-extra-fields [...]

Reply

David Radovanovic  Dec 07, 2011

Thanks!! Does the function and “function save_extra_category_fileds” get placed in the functions.php file as well?

Reply

    Ohad Raz  Dec 07, 2011

    @David: both functions and action hooks posted above go in the functions.php well not much just two.

    Reply

davidradovanovic  Dec 07, 2011

So, here is what I added to my functions.php file:

//add extra fields to category edit form hook
add_action ( ‘edit_category_form_fields’, ‘extra_category_fields’);
//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”);
   ?>

   <input type="text" name="Cat_meta[img]" id="Cat_meta[img]" size="3" style="width:60%;" value="”>
   <input type="text" name="Cat_meta[extra1]" id="Cat_meta[extra1]" size="25" style="width:60%;" value="”>
   <input type="text" name="Cat_meta[extra2]" id="Cat_meta[extra2]" size="25" style="width:60%;" value="”>
   <?php
}

// save extra category extra fields hook
add_action ( 'edited_category', 'save_extra_category_fields');
// save extra category extra fields callback function
function save_extra_category_fields( $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 );
     }
}

add_action ( 'category_add_form_fields', 'extra_category_fields');

Thanks Ohad and contributors!

Now I just need to find a way to add the category image as the featured image # get_header(); # in the Twenty Eleven theme. Instead of right above category title.

Reply

    Ohad Raz  Dec 08, 2011

    @David:
    try this, edit header.php (you should use a child theme).
    look for:

    echo get_the_post_thumbnail( $post->ID, 'post-thumbnail' );
    					else : ?>
    

    and just before

    else:

    insert this:

    elseif( is_category() ) : ?>
    <?php
    //first get the current category ID
    $cat_id = get_query_var('cat');
    //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 (isset($cat_data['img'])){
    	?> <img src="<?php echo $cat_data['img']; ?>" width="<?php echo HEADER_IMAGE_WIDTH; ?>" height="<?php echo HEADER_IMAGE_HEIGHT; ?>" alt="" /><?php
    }
    

    I didn’t test it but i think this should work.

    Reply

      David Radovanovic  Jan 11, 2012

      Thanks! Off topic though — how do you accomplish the above social login icons?

      Reply

      Ohad Raz  Jan 12, 2012

      @David: way off topic :) , anyway its done using a custom coding and the excellent Socialite script which late loads the social buttons after the page load ends. I’m Currently codding a plugin for that will be available soon.

      Reply

Dan  Dec 07, 2011

I am new to wordpress, just started this week and this is exactly what I am looking for. Could you tell me in which file I should put the above two functions ( save_extra_category_fileds( $term_id ) and function extra_category_fields( $tag )) ? Thanks a lot for this nice post.

Reply

    Ohad Raz  Dec 08, 2011

    @dan:

    Both should go inside you theme’s functions.php or a custom plugin file, and don’t forget the action hooks.

    Reply

Leon  Jan 11, 2012

Great tuts, but i have a question how can i add select drop down field ?

Reply

    Ohad Raz  Jan 11, 2012

    @leon:

    simple just like any other field, for example:

    <tr class="form-field">
    	<th scope="row" valign="top"><label for="select_field"><?php _e('extra field'); ?></label></th>
    	<td>
            <select name="Cat_meta[select_field]" id="Cat_meta[select_field]" style="width:60%;">
    			<option value="value_1" <?php echo ($cat_meta['select_field'] == "value_1") ? 'selected="selected"': ''; ?>>Value One</option>
    			<option value="value_2" <?php echo ($cat_meta['select_field'] == "value_2") ? 'selected="selected"': ''; ?>>Value Two</option>
    			<option value="value_3" <?php echo ($cat_meta['select_field'] == "value_3") ? 'selected="selected"': ''; ?>>Value Three</option>
    			<option value="value_4" <?php echo ($cat_meta['select_field'] == "value_4") ? 'selected="selected"': ''; ?>>Value Four</option>
    		</select><br />
            <span class="description"><?php _e('An Extra select field'); ?></span>
        </td>
    </tr>
    

    Reply

      Leon  Jan 14, 2012

      Thank You

      Reply

Hian Battiston  Jan 18, 2012

Congratulations Ohad, great tutorial!

But I have a problem. When I click update it returns that:

Warning: Cannot modify header information – headers already sent by (output started at /…/public_html/v2/wp-content/themes/melhoramentos/functions.php:704) in /…/public_html/v2/wp-includes/pluggable.php on line 866

What is the problem?!

And other thing, there is a way to upload the image and not just post the url? Like in posts?

Thanks!

Reply

    Ohad Raz  Jan 20, 2012

    @Hian:

    Without seeing your code i can only assume that you have done something wrong.
    create a pastebin of you code and send it to me I’ll take a look.

    as for image field I’ll post a follow up post to this in a day or two with a script that i made to make thing a lot easier.

    Reply





Login with:
Facebook Google Twitter Yahoo!

Leave a Reply

  Cancel Reply

 

  • About the author

    Ohad Raz

    I'm a WordPress Consultant, a WordPress Developer and a WordPress Freelancer
    Currently in my third year of Software Engineering B.Sce Degree.
    I've been developing Websites and web applications on WordPress for over 5 years.
    I live in Kiryat Gat , Israel.

    • Write an E-Mail
  • Other Methods of contact

    My profile on WordPress Answers

    profile for Bainternet at WordPress, Q&A for WordPress developers and administrators

    • My Code Poet listing

    • My Careers 2.0 Profile

    • My Gravatar.com Profile

    • My About.Me Profile

    • Contact Form

  • Enter your email address to subscribe to this blog and receive notifications of new posts by email.




  • Recent Comments

    • WordPress Developer Alex Nowak on WordPress Taxonomies Extra Fields the easy way
    • WordPress Developer Caswell Lerotholi on How I add a WordPress MetaBox
    • WordPress Developer Caswell Lerotholi on How I add a WordPress MetaBox
    • WordPress Developer Caswell on How I add a WordPress MetaBox
    • WordPress Developer Eric on My Options Panel
  • About Ohad Raz

    Ohad Raz

    I'm a WordPress Consultant, a WordPress Developer and a WordPress Freelancer
    Currently in my third year of Software Engineering B.Sce Degree.
    I've been developing Websites and web applications on WordPress for over 5 years.
    I live in Kiryat Gat , Israel.

    • Enter your email address to subscribe to this blog and receive notifications of new posts by email.



    • About Me
    • Contact me
    • Donations
    • disclaimer
    © 2011 by Bainternet WordPress Consultant