WordPress用户相关代码测试和收藏

  • A+
所属分类:WordPress

以添加微信号为例,代码全部添加在主题的functions.php文件中。

注册页加自定义字段

WordPress的注册页地址是/wp-login.php?action=register,注册页页面。

WordPress用户相关代码测试和收藏

代码

add_action( 'register_form', 'myplugin_add_registration_fields' );
function myplugin_add_registration_fields() {
    //Get and set any values already sent
    $weixin = ( isset( $_POST['weixin'] ) ) ? $_POST['weixin'] : '';
    ?>
    <p>
        <label for="user_extra">微信<br/>
            <input type="text" name="weixin" id="weixin" class="input" value="<?php echo esc_attr( stripslashes( $weixin ) ); ?>" size="25" /></label>
    </p>
    <?php
}

//2. Add validation. In this case, we make sure first_name is required.
add_filter( 'registration_errors', 'myplugin_registration_errors', 10, 3 );
function myplugin_registration_errors( $errors, $sanitized_user_login, $user_email ) {

    if ( empty( $_POST['weixin'] ) || ! empty( $_POST['weixin'] ) && trim( $_POST['weixin'] ) == '' ) {
        $errors->add( 'weixin_error', __( '<strong>ERROR</strong>: You must include a first name.', 'mydomain' ) );
    }

    return $errors;
}

//3. Finally, save our extra registration user meta.
add_action( 'user_register', 'myplugin_user_register' );
function myplugin_user_register( $user_id ) {
    if ( ! empty( $_POST['weixin'] ) ) {
        update_user_meta( $user_id, 'weixin', trim( $_POST['weixin'] ) );
    }
}

后台添加用户页面

WordPress用户相关代码测试和收藏

代码

/*  添加用户时的表单字段  */
add_action('user_new_form','my_user_form');
function my_user_form(){
    $weixin = ( ! empty( $_POST['weixin'] ) ) ? trim( $_POST['weixin'] ) : '';
    ?>
    <p>
        <label for="weixin">微信:
            <input type="text" name="weixin" id="weixin" class="input" value="<?php echo esc_attr( wp_unslash( $weixin ) ); ?>" size="25" /></label>
    </p>
    <?php
}
add_action( 'user_register', 'my_user_weixinadd' );
function my_user_weixinadd( $user_id ) {
    if ( ! empty( $_POST['weixin'] ) ) {
        update_user_meta( $user_id, 'weixin', trim( $_POST['weixin'] ) );
    }
}

后台编辑用户页面

WordPress用户相关代码测试和收藏

代码

add_filter( 'user_contactmethods', 'wpdaxue_add_contact_fields' );
function wpdaxue_add_contact_fields( $contactmethods ) {
    //添加一些联系方式字段
    $contactmethods['mymobile'] = '手机号';
    $contactmethods['mycity'] = '所在城市';
    $contactmethods['myaddress'] = '地址详情';
    $contactmethods['myunit'] = '所属单位';
    $contactmethods['weixin'] = '微信';
    //取消一些字段
    unset( $contactmethods['url'] );
    unset( $contactmethods['yim'] );
    unset( $contactmethods['aim'] );
    unset( $contactmethods['jabber'] );
    return $contactmethods;
}
weinxin
独角兽驿站
公众号

发表评论

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen: