(WordPress教程)可以通过添加本地头像功能来替代Gravatar头像功能 - 汇站网

(WordPress教程)可以通过添加本地头像功能来替代Gravatar头像功能

2023-09-14 0 727

正文:

目前几乎所有的 WordPress 网站都使用 Gravatar 的全球头像来关联用户的头像,但是由于 Gravatar 的服务器在国外,在国内经常因为一些 XXX 的原因无法连接。为了解决这个问题,汇站提到了使用国内 cdn 服务镜像 Gravatar 的头像。另一方面,开放的注册网站可以使用 simple-local-avatars 插件将用户的头像完全本地化,因此无需担心 Gravatar 头像超时导致网站打开缓慢。
今天汇站就教大家用代码半本地化 Gravatar 头像,那么什么是半本地化呢?也就是说,用户是否有 Gravatar 头像是通过用户的邮箱来判断的。如果有,就用 Gravatar 头像。如果用户有本地头像并且有 Gravatar 头像,则首先使用本地头像。

代码如下:

<?php
class Simple_Local_Avatars {
    private $user_id_being_edited;
 
    public function __construct() {
        add_filter( 'get_avatar', array( $this, 'get_avatar' ), 10, 5 );
 
        add_action( 'admin_init', array( $this, 'admin_init' ) );
 
        add_action( 'show_user_profile', array( $this, 'edit_user_profile' ) );
        add_action( 'edit_user_profile', array( $this, 'edit_user_profile' ) );
 
        add_action( 'personal_options_update', array( $this, 'edit_user_profile_update' ) );
        add_action( 'edit_user_profile_update', array( $this, 'edit_user_profile_update' ) );
 
        add_filter( 'avatar_defaults', array( $this, 'avatar_defaults' ) );
    }
 
    public function get_avatar( $avatar = '', $id_or_email, $size = 96, $default = '', $alt = false ) {
 
        if ( is_numeric($id_or_email) )
            $user_id = (int) $id_or_email;
        elseif ( is_string( $id_or_email ) && ( $user = get_user_by( 'email', $id_or_email ) ) )
            $user_id = $user->ID;
        elseif ( is_object( $id_or_email ) && ! empty( $id_or_email->user_id ) )
            $user_id = (int) $id_or_email->user_id;
 
        if ( empty( $user_id ) )
            return $avatar;
 
        $local_avatars = get_user_meta( $user_id, 'simple_local_avatar', true );
 
        if ( empty( $local_avatars ) || empty( $local_avatars['full'] ) )
            return $avatar;
 
        $size = (int) $size;
 
        if ( empty( $alt ) )
            $alt = get_the_author_meta( 'display_name', $user_id );
 
        // generate a new size
        if ( empty( $local_avatars[$size] ) ) {
            $upload_path = wp_upload_dir();
            $avatar_full_path = str_replace( $upload_path['baseurl'], $upload_path['basedir'], $local_avatars['full'] );
            $image_sized = image_resize( $avatar_full_path, $size, $size, true );      
            // deal with original being >= to original image (or lack of sizing ability)
            $local_avatars[$size] = is_wp_error($image_sized) ? $local_avatars[$size] = $local_avatars['full'] : str_replace( $upload_path['basedir'], $upload_path['baseurl'], $image_sized );
            // save updated avatar sizes
            update_user_meta( $user_id, 'simple_local_avatar', $local_avatars );
        } elseif ( substr( $local_avatars[$size], 0, 4 ) != 'http' ) {
            $local_avatars[$size] = home_url( $local_avatars[$size] );
        }
 
        $author_class = is_author( $user_id ) ? ' current-author' : '' ;
        $avatar = "<img alt='" . esc_attr( $alt ) . "' src='" . $local_avatars[$size] . "' class='avatar avatar-{$size}{$author_class} photo' height='{$size}' width='{$size}' />";
 
        return apply_filters( 'simple_local_avatar', $avatar );
    }
 
    public function admin_init() {
        //load_plugin_textdomain( 'simple-local-avatars', false, dirname( plugin_basename( __FILE__ ) ) . '/localization/' );
 
        register_setting( 'discussion', 'simple_local_avatars_caps', array( $this, 'sanitize_options' ) );
        add_settings_field( 'simple-local-avatars-caps', __('Local Avatar Permissions','simple-local-avatars'), array( $this, 'avatar_settings_field' ), 'discussion', 'avatars' );
    }
 
    public function sanitize_options( $input ) {
        $new_input['simple_local_avatars_caps'] = empty( $input['simple_local_avatars_caps'] ) ? 0 : 1;
        return $new_input;
    }
 
    public function avatar_settings_field( $args ) {       
        $options = get_option('simple_local_avatars_caps');
 
        echo '
            <label for="simple_local_avatars_caps">
                <input type="checkbox" name="simple_local_avatars_caps" id="simple_local_avatars_caps" value="1" ' . @checked( $options['simple_local_avatars_caps'], 1, false ) . ' />
                ' . __('仅具有头像上传权限的用户具有设置本地头像权限(作者及更高等级角色)。','simple-local-avatars') . '
            </label>
        ';
    }
 
    public function edit_user_profile( $profileuser ) {
    ?>
    <h3><?php _e( '头像','simple-local-avatars' ); ?></h3>
 
    <table class="form-table">
        <tr>
            <th><label for="simple-local-avatar"><?php _e('上传头像','simple-local-avatars'); ?></label></th>
            <td style="width: 50px;" valign="top">
                <?php echo get_avatar( $profileuser->ID ); ?>
            </td>
            <td>
            <?php
                $options = get_option('simple_local_avatars_caps');
 
                if ( empty($options['simple_local_avatars_caps']) || current_user_can('upload_files') ) {
                    do_action( 'simple_local_avatar_notices' );
                    wp_nonce_field( 'simple_local_avatar_nonce', '_simple_local_avatar_nonce', false );
            ?>
                    <input type="file" name="simple-local-avatar" id="simple-local-avatar" /><br />
            <?php
                    if ( empty( $profileuser->simple_local_avatar ) )
                        echo '<span class="description">' . __('尚未设置本地头像,请点击“浏览”按钮上传本地头像。','simple-local-avatars') . '</span>';
                    else
                        echo '
                            <input type="checkbox" name="simple-local-avatar-erase" value="1" /> ' . __('移除本地头像','simple-local-avatars') . '<br />
                            <span class="description">' . __('如需要修改本地头像,请重新上传新头像。如需要移除本地头像,请选中上方的“移除本地头像”复选框并更新个人资料即可。<br/>移除本地头像后,将恢复使用 Gravatar 头像。','simple-local-avatars') . '</span>
                        ';     
                } else {
                    if ( empty( $profileuser->simple_local_avatar ) )
                        echo '<span class="description">' . __('尚未设置本地头像,请在 Gravatar.com 网站设置头像。','simple-local-avatars') . '</span>';
                    else
                        echo '<span class="description">' . __('你没有头像上传全乡,如需要修改本地头像,请联系站点管理员。','simple-local-avatars') . '</span>';
                }
            ?>
            </td>
        </tr>
    </table>
    <script type="text/javascript">var form = document.getElementById('your-profile');form.encoding = 'multipart/form-data';form.setAttribute('enctype', 'multipart/form-data');</script>
    <?php       
    }
 
    public function edit_user_profile_update( $user_id ) {
        if ( ! isset( $_POST['_simple_local_avatar_nonce'] ) || ! wp_verify_nonce( $_POST['_simple_local_avatar_nonce'], 'simple_local_avatar_nonce' ) )            //security
            return;
 
        if ( ! empty( $_FILES['simple-local-avatar']['name'] ) ) {
            $mimes = array(
                'jpg|jpeg|jpe' => 'image/jpeg',
                'gif' => 'image/gif',
                'png' => 'image/png',
                'bmp' => 'image/bmp',
                'tif|tiff' => 'image/tiff'
            );
 
            // front end (theme my profile etc) support
            if ( ! function_exists( 'wp_handle_upload' ) )
                require_once( ABSPATH . 'wp-admin/includes/file.php' );
 
            $this->avatar_delete( $user_id );    // delete old images if successful
 
            // need to be more secure since low privelege users can upload
            if ( strstr( $_FILES['simple-local-avatar']['name'], '.php' ) )
                wp_die('For security reasons, the extension ".php" cannot be in your file name.');
 
            $this->user_id_being_edited = $user_id; // make user_id known to unique_filename_callback function
            $avatar = wp_handle_upload( $_FILES['simple-local-avatar'], array( 'mimes' => $mimes, 'test_form' => false, 'unique_filename_callback' => array( $this, 'unique_filename_callback' ) ) );
 
            if ( empty($avatar['file']) ) {     // handle failures
                switch ( $avatar['error'] ) {
                    case 'File type does not meet security guidelines. Try another.' :
                        add_action( 'user_profile_update_errors', create_function('$a','$a->add("avatar_error",__("请上传有效的图片文件。","simple-local-avatars"));') );              
                        break;
                    default :
                        add_action( 'user_profile_update_errors', create_function('$a','$a->add("avatar_error","<strong>".__("上传头像过程中出现以下错误:","simple-local-avatars")."</strong> ' . esc_attr( $avatar['error'] ) . '");') );
                }
 
                return;
            }
 
            update_user_meta( $user_id, 'simple_local_avatar', array( 'full' => $avatar['url'] ) );      // save user information (overwriting old)
        } elseif ( ! empty( $_POST['simple-local-avatar-erase'] ) ) {
            $this->avatar_delete( $user_id );
        }
    }
 
    /**
     * remove the custom get_avatar hook for the default avatar list output on options-discussion.php
     */
    public function avatar_defaults( $avatar_defaults ) {
        remove_action( 'get_avatar', array( $this, 'get_avatar' ) );
        return $avatar_defaults;
    }
 
    /**
     * delete avatars based on user_id
     */
    public function avatar_delete( $user_id ) {
        $old_avatars = get_user_meta( $user_id, 'simple_local_avatar', true );
        $upload_path = wp_upload_dir();
 
        if ( is_array($old_avatars) ) {
            foreach ($old_avatars as $old_avatar ) {
                $old_avatar_path = str_replace( $upload_path['baseurl'], $upload_path['basedir'], $old_avatar );
                @unlink( $old_avatar_path );   
            }
        }
 
        delete_user_meta( $user_id, 'simple_local_avatar' );
    }
 
    public function unique_filename_callback( $dir, $name, $ext ) {
        $user = get_user_by( 'id', (int) $this->user_id_being_edited );
        $name = $base_name = sanitize_file_name( $user->user_login . '_avatar' );
        $number = 1;
 
        while ( file_exists( $dir . "/$name$ext" ) ) {
            $name = $base_name . '_' . $number;
            $number++;
        }
 
        return $name . $ext;
    }
}
 
$simple_local_avatars = new Simple_Local_Avatars;
 
function get_simple_local_avatar( $id_or_email, $size = '96', $default = '', $alt = false ) {
    global $simple_local_avatars;
    $avatar = $simple_local_avatars->get_avatar( '', $id_or_email, $size, $default, $alt );
 
    if ( empty ( $avatar ) )
        $avatar = get_avatar( $id_or_email, $size, $default, $alt );
 
    return $avatar;
}

 

将以上代码放入主题functions.php里面,然后保存回到网站后台点击个人资料即可看到,如下图:
(WordPress教程)可以通过添加本地头像功能来替代Gravatar头像功能

转载请注明:汇站网 » (WordPress 教程)可以通过添加本地头像功能来替代 Gravatar 头像功能

收藏 (0)

微信扫一扫

支付宝扫一扫

点赞 (0)

感谢您的来访,获取更多精彩资源请收藏本站。

本站声明

本资源仅用于个人学习和研究使用,禁止用于任何商业环境!

 1.  本网站名称:汇站网
 2.  本站永久网址:https://www.huizhanii.com/
 3.  本站所有资源来源于网友投稿和高价购买,所有资源仅对编程人员及源代码爱好者开放下载做参考和研究及学习,本站不提供任何技术服务!
 4.  未经原版权作者许可,禁止用于任何商业环境,任何人不得擅作它用,下载者不得用于违反国家法律,否则发生的一切法律后果自行承担!
 5.  为尊重作者版权,请在下载24小时内删除!请购买原版授权作品,支持你喜欢的作者,谢谢!
 6.  若资源侵犯了您的合法权益, 请持您的版权证书和相关原作品信息来信通知我们请来信     通知我们我们会及时删除,给您带来的不便,我们深表歉意!
 7.  如下载链接失效、广告或者压缩包问题请联系站长处理!
 8.  如果你也有好源码或者教程,可以发布到网站,分享有金币奖励和额外收入!
 9.  本站资源售价只是赞助,收取费用仅维持本站的日常运营所需!
 10.  因源码具有可复制性,一经赞助 ,不得以任何形式退款。
 11.  更多详情请点击查看

汇站网 WordPress教程 (WordPress教程)可以通过添加本地头像功能来替代Gravatar头像功能 https://www.huizhanii.com/33163.html

汇站

站长资源下载中心-找源码上汇站

常见问题
  • 如果付款后没有弹出下载页面,多刷新几下,有问题联系客服!
查看详情
  • 本站所有资源版权均属于原作者所有,这里所提供资源均只能用于参考学习用,请勿直接商用。若由于商用引起版权纠纷,一切责任均由使用者承担。
查看详情

相关文章

发表评论
1 条评论
  随机评论 表情开关按钮图片
表情表情表情表情表情表情表情表情表情表情表情表情表情表情表情表情表情表情表情表情表情表情表情表情表情表情表情表情表情表情表情表情表情表情表情表情表情表情表情
登录后评论
2023年9月27日 09:51

站长威武,站长帅~ :cool:

联系官方客服

为您解决烦忧 - 24小时在线 专业服务

(汇站网)一个专注站长资源的平台网站,提供最新的网站模板和整站源码,内容包含各类精品网页模板,企业网站模板,网站模板,DIV+CSS模板,织梦模板,帝国cms模板,discuz模板,wordpress模板,个人博客论坛模板,上千种免费网页模板下载尽在汇站网.找源码上汇站.huizhanii.com