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

时间:2015-06-11 00:49:35

标签: php wordpress categories

我发现这个脚本效果非常好。它在管理员的类别页面中添加了几个额外的字段。

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上的这个循环中显示前端的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值。

提前致谢!

1 个答案:

答案 0 :(得分:1)

您使用字段键和术语ID保存选项表中类别字段的值。例如。 first_name_5

例如,如果您想在“stuff”div中的空段落中显示第一个名称字段,您可以使用:

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