I've found this script which works perfectly well. It adds a couple of extra fields to the categories page in admin.
add_action( 'category_add_form_fields', 'category_form_custom_field_add', 10 );
add_action( 'category_edit_form_fields', 'category_form_custom_field_edit', 10, 2 );
function category_form_custom_field_add( $taxonomy ) {
?>
<div class="form-field">
<label for="first_name">First Name</label>
<input name="first_name" id="first_name" type="text" value="" size="10" />
</div>
<div class="form-field">
<label for="last_name">Last Name</label>
<input name="last_name" id="last_name" type="text" value="" size="10" />
</div>
<?php
}
function category_form_custom_field_edit( $tag, $taxonomy ) {
$tr_first_name = 'first_name_' . $tag->term_id;
$first_name = get_option( $tr_first_name );
$tr_last_name = 'last_name_' . $tag->term_id;
$last_name = get_option( $tr_last_name );
?>
<tr class="form-field">
<th scope="row" valign="top"><label for="first_name">First Name</label></th>
<td>
<input type="text" name="first_name" id="first_name" value="<?php echo esc_attr( $first_name ) ? esc_attr( $first_name ) : ''; ?>" />
</td>
</tr>
<tr class="form-field">
<th scope="row" valign="top"><label for="last_name">Last Name</label></th>
<td>
<input type="text" name="last_name" id="last_name" value="<?php echo esc_attr( $last_name ) ? esc_attr( $last_name ) : ''; ?>" />
</td>
</tr>
<?php
}
/** Save Custom Fields */
add_action( 'created_category', 'category_form_custom_field_save', 10, 2 );
add_action( 'edited_category', 'category_form_custom_field_save', 10, 2 );
function category_form_custom_field_save( $term_id, $tt_id ) {
if ( isset( $_POST['first_name'] ) ) {
$tr_first_name = 'first_name_' . $term_id;
update_option( $tr_first_name, $_POST['first_name'] );
}
if ( isset( $_POST['last_name'] ) ) {
$last_name = 'last_name_' . $term_id;
update_option( $last_name, $_POST['last_name'] );
}
}
But I don't know what I have to do to display the first_name and last_name values on the front-end in this loop I have on page.php
<?php // List all category names and custom fields
$categories = get_categories('hide_empty=0&order=ASC');
foreach ($categories as $cat) {
$posts = new WP_Query( array('post_type' => 'post', 'showposts' => -1, 'post_status' => array('trash', 'publish'), 'cat' => $cat->cat_ID));
?>
<div class="stuff">
<h2><a href="<?php echo $cat->category_nicename; ?>"><?php echo $cat->cat_name; ?></a></h2>
<p></p>
</div>
<?php }
?>
Ideally I'd like the first_name and last_name values to display inside the
tags.
Thanks in advance!
You're saving the value of the category fields in the options table using the field key combined with the term ID. E.g.
first_name_5
.If for example you wanted to display the first name field in the empty paragraph inside your 'stuff' div you could use: