让 WordPress 注册用户到另外的Gravatar头像网站申请上传头像,并不符合常规习惯,因此在自己网站添加上传自定义头像功能还是很有必要。
为 WordPress 添加一个简单的自定义Avatars头像功能
之前推荐的用户上传头像插件:
Plugins
让WordPress支持注册用户上传自定义头像功能
默认Wordpress支持显示Gravatar头像,但目前由于众所周知的原因,申请Gravatar头像比较困难只能显示默认的…
很好用,这里再分享一个简单的自定义Avatars头像功能,将下面代码添加到当前主题函数模板functions.php中:
一、在用户资料页面添加自定义Avatar字段
function be_custom_avatar_field( $user ) { ?> <h2>自定义头像</h2> <table class=\"form-table\" role=\"presentation\"> <tbody> <tr class=\"be_custom_avatar\"> <th><label for=\"be_custom_avatar\">头像图片链接: </label></th> <td> <input type=\"text\" name=\"be_custom_avatar\" id=\"be_custom_avatar\" class=\"regular-text ltr\" value=\"<?php echo esc_url_raw( get_the_author_meta( \'be_custom_avatar\', $user->ID ) ); ?>\" /> <p class=\"description\" id=\"be_custom_avatar-description\">输入头像的图片链接,图片尺寸 70x70 像素。</p> </td> </tr> </tbody> </table> <?php } add_action( \'show_user_profile\', \'be_custom_avatar_field\' ); add_action( \'edit_user_profile\', \'be_custom_avatar_field\' ); function be_save_custom_avatar_field( $user_id ) { if ( current_user_can( \'edit_user\', $user_id ) ) { update_usermeta( $user_id, \'be_custom_avatar\', esc_url_raw( $_POST[\'be_custom_avatar\'] ) ); } } add_action( \'personal_options_update\', \'be_save_custom_avatar_field\' ); add_action( \'edit_user_profile_update\', \'be_save_custom_avatar_field\' );
二、通过add_filter过滤器,显示自定义头像。
function be_gravatar_filter($avatar, $id_or_email, $size, $default, $alt) { $email = is_object( $id_or_email ) ? $id_or_email->comment_author_email : $id_or_email; if( is_email( $email ) && ! email_exists( $email ) ) return $avatar; $custom_avatar = get_the_author_meta(\'be_custom_avatar\'); if ($custom_avatar) $return = \'<img src=\"\'.$custom_avatar.\'\" width=\"\'.$size.\'\" height=\"\'.$size.\'\" alt=\"\'.$alt.\'\" />\'; elseif ($avatar) $return = $avatar; else $return = \'<img src=\"\'.$default.\'\" width=\"\'.$size.\'\" height=\"\'.$size.\'\" alt=\"\'.$alt.\'\" />\'; return $return; } add_filter(\'get_avatar\', \'be_gravatar_filter\', 10, 5);
上面的代码与插件相比,功能比较简单,并没有图片上传功能,只能通过输入图片地址实现自定义头像。
代码源自
暂无评论内容