Wordpress自定义字段。在自定义页面上显示用户配置文件的自定义字段

时间:2016-01-10 15:45:47

标签: php wordpress custom-fields

在我的wordpress博客上,我有一些功能,允许登录的用户能够选择他们希望在博客页面上看到的帖子类别。因此,每个用户只能查看他们订阅的类别的帖子,而不是所有类别。

我使用了这段代码。

Zoo::Cat

这是结果。

How it looks for the user as they subscribe to their preferred categories

此代码工作正常,但是,我希望这些选项显示在另一个页面而不是用户配置文件上,因此我创建了另一个专门用于处理此页面的页面模板。

add_action( 'show_user_profile', 'my_show_extra_profile_fields' );
add_action( 'edit_user_profile', 'my_show_extra_profile_fields' );

function my_show_extra_profile_fields( $user ) { 
?>
<h3>Extra profile information</h3>

<table class="form-table">
    <tr>
        <th>
            <label for="post_category">Display Categories</label><br />
            <span class="description">Which categories would you like to see posts from?</span>
        </th>
        <td>
            <ul class="categorychecklist form-no-clear">
                <?php wp_terms_checklist( 0, array( 'checked_ontop' => false, 'taxonomy' => 'category', 'selected_cats' => get_user_meta( $user->ID, 'post_category', true ) ) ) ?>
            </ul>   
        </td>
    </tr>
</table>
<?php 
}

add_action( 'personal_options_update', 'my_save_extra_profile_fields' );
add_action( 'edit_user_profile_update', 'my_save_extra_profile_fields' );

function my_save_extra_profile_fields( $user_id ) {

if ( !current_user_can( 'edit_user', $user_id ) )
    return false;

if( !isset( $_POST['post_category'] ) )
    return false;

if( !is_array( $_POST['post_category'] ) )
    return false;

 update_usermeta( $user_id, 'post_category', array_map( 'absint',
 $_POST['post_category'] ) );
}

add_action( 'pre_get_posts', 'set_user_categories', 1000 );
function set_user_categories( $wp_obj ) {
if( !is_front_page() )
    return;

if( 'nav_menu_item' == $wp_obj->query_vars['post_type'] )
    return;

global $current_user;

$user_cats = get_user_meta( $current_user->ID, 'post_category', true );
if( !$user_cats )
    return;

$wp_obj->set( 'category__in', $user_cats );
}

<?php
/*
Template Name: Subscribe
*/
?>
<?php get_header() ?>

   <div class="page-container">
  <div><?php the_field('my_show_extra_profile_fields'); ?></div>

正如你所看到的,我试图显示字段“my_show_extra_profile_fields”,但它没有显示出来。

如何在我的页面模板subscribe.php上显示这些选项,而不是用户个人资料?

1 个答案:

答案 0 :(得分:1)

试试这段代码。 extra_field_name可能是&#34; post_category&#34;

global $current_user;
echo get_user_meta( $current_user->ID, 'extra_field_name', true );

就像

一样
echo get_user_meta( $current_user->ID, 'post_category', true );