在前端显示自定义类别字段值

Show custom category field values on the front-end

我发现这个脚本运行良好。它向管理中的类别页面添加了几个额外的字段。

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'] );
    }
}

但我不知道我必须做什么才能在 page.php[=12 上的这个循环中在前端显示 first_name 和 last_name 值=]

<?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 }
?>

理想情况下,我希望 first_name 和 last_name 值显示在

标签内。

提前致谢!

您正在使用字段键和术语 ID 组合保存选项 table 中类别字段的值。例如。 first_name_5.

例如,如果您想在 'stuff' div 的空段落中显示名字字段,您可以使用:

<p>First Name: <?php echo get_option( 'first_name_' . $cat->term_id ); ?></p>