How would I create a custom field in category form ?



This article is a tutorial of how to add custom fields to category form. (categories are taxonomies too). 

Step 1: Goto active theme's Directory & the following codes in functions.php

<?php
function category_fields_new( $taxonomy ) {    /
wp_nonce_field( 'category_meta_new', 'category_meta_new_nonce' );   
?>
        <div class="form-field">
        <label for="category_fa">My Custom Field</label>
        <input name="category_imageUrl" type="text" >
        <p class="description">Enter Your Custom Field </p>
    </div>
<?php
}
add_action( 'category_add_form_fields', 'category_fields_new', 10 );

This above code will display these fields in category add form, so the next step is add this form in category edit page

Step 2: 
function category_fields_edit( $term, $taxonomy ) {    
    wp_nonce_field( 'category_meta_edit', 'category_meta_edit_nonce' );    
    $category_imageUrl = get_option( "{$taxonomy}_{$term->term_id}_imageUrl" ); 
    ?>
    <tr class="form-field">
    <th scope="row" valign="top">   <label for="category_fa"> My custom field  </label>  </th>
        <td>
            <input name="imgUrll" id="category_fa" type="text" value="<?php echo ( ! empty( $category_imageUrl ) ) ? $category_imageUrl : ''; ?>" style="width:100%;" />
            <input type="hidden" id="_thumbnail_id" name="_thumbnail_id" value="-1">
            
           <!-- IF `$category_imageUrl` is not empty, display it. Otherwise display an empty string -->
            <p class="description">Enter Image URL</p> 
        </td> 
    </tr>
<?php
}

add_action( 'category_edit_form_fields', 'category_fields_edit', 10, 2 );




Post a Comment

Previous Post Next Post