WordPress自定义用户头像

虽然WordPress支持Gravatar头像,但由于G站被墙没法访问,所以有时需要更换头像会非常麻烦,所以设置用户后台自定义头像就很有必要了。

  1 class Simple_Local_Avatars {
  2     private $user_id_being_edited;
  3 
  4     public function __construct() {
  5         add_filter( 'get_avatar', array( $this, 'get_avatar' ), 10, 5 );
  6 
  7         add_action( 'admin_init', array( $this, 'admin_init' ) );
  8 
  9         add_action( 'show_user_profile', array( $this, 'edit_user_profile' ) );
 10         add_action( 'edit_user_profile', array( $this, 'edit_user_profile' ) );
 11 
 12         add_action( 'personal_options_update', array( $this, 'edit_user_profile_update' ) );
 13         add_action( 'edit_user_profile_update', array( $this, 'edit_user_profile_update' ) );
 14 
 15         add_filter( 'avatar_defaults', array( $this, 'avatar_defaults' ) );
 16     }
 17 
 18     public function get_avatar( $avatar = '', $id_or_email, $size = 96, $default = '', $alt = false ) {
 19 
 20         if ( is_numeric($id_or_email) )
 21             $user_id = (int) $id_or_email;
 22         elseif ( is_string( $id_or_email ) && ( $user = get_user_by( 'email', $id_or_email ) ) )
 23             $user_id = $user->ID;
 24         elseif ( is_object( $id_or_email ) && ! empty( $id_or_email->user_id ) )
 25             $user_id = (int) $id_or_email->user_id;
 26 
 27         if ( empty( $user_id ) )
 28             return $avatar;
 29 
 30         $local_avatars = get_user_meta( $user_id, 'simple_local_avatar', true );
 31 
 32         if ( empty( $local_avatars ) || empty( $local_avatars['full'] ) )
 33             return $avatar;
 34 
 35         $size = (int) $size;
 36 
 37         if ( empty( $alt ) )
 38             $alt = get_the_author_meta( 'display_name', $user_id );
 39 
 40         // generate a new size
 41         if ( empty( $local_avatars[$size] ) ) {
 42             $upload_path = wp_upload_dir();
 43             $avatar_full_path = str_replace( $upload_path['baseurl'], $upload_path['basedir'], $local_avatars['full'] );
 44             $image_sized = image_resize( $avatar_full_path, $size, $size, true );       
 45             // deal with original being >= to original image (or lack of sizing ability)
 46             $local_avatars[$size] = is_wp_error($image_sized) ? $local_avatars[$size] = $local_avatars['full'] : str_replace( $upload_path['basedir'], $upload_path['baseurl'], $image_sized ); 
 47             // save updated avatar sizes
 48             update_user_meta( $user_id, 'simple_local_avatar', $local_avatars );
 49         } elseif ( substr( $local_avatars[$size], 0, 4 ) != 'http' ) {
 50             $local_avatars[$size] = home_url( $local_avatars[$size] );
 51         }
 52 
 53         $author_class = is_author( $user_id ) ? ' current-author' : '' ;
 54         $avatar = "<img alt='" . esc_attr( $alt ) . "' src='" . $local_avatars[$size] . "' class='avatar avatar-{$size}{$author_class} photo' height='{$size}' width='{$size}' />";
 55 
 56         return apply_filters( 'simple_local_avatar', $avatar );
 57     }
 58 
 59     public function admin_init() {
 60         //load_plugin_textdomain( 'simple-local-avatars', false, dirname( plugin_basename( __FILE__ ) ) . '/localization/' );
 61 
 62         register_setting( 'discussion', 'simple_local_avatars_caps', array( $this, 'sanitize_options' ) );
 63         add_settings_field( 'simple-local-avatars-caps', __('上传头像权限','simple-local-avatars'), array( $this, 'avatar_settings_field' ), 'discussion', 'avatars' );
 64     }
 65 
 66     public function sanitize_options( $input ) {
 67         $new_input['simple_local_avatars_caps'] = empty( $input['simple_local_avatars_caps'] ) ? 0 : 1;
 68         return $new_input;
 69     }
 70 
 71     public function avatar_settings_field( $args ) {        
 72         $options = get_option('simple_local_avatars_caps');
 73 
 74         echo '
 75             <label for="simple_local_avatars_caps">
 76                 <input type="checkbox" name="simple_local_avatars_caps" id="simple_local_avatars_caps" value="1" ' . @checked( $options['simple_local_avatars_caps'], 1, false ) . ' />
 77                 ' . __('仅具有头像上传权限的用户具有设置本地头像权限(作者及更高等级角色)。','simple-local-avatars') . '
 78             </label>
 79         ';
 80     }
 81 
 82     public function edit_user_profile( $profileuser ) {
 83     ?>
 84     <h3><?php _e( '头像','simple-local-avatars' ); ?></h3>
 85 
 86     <table class="form-table">
 87         <tr>
 88             <th><label for="simple-local-avatar"><?php _e('上传头像','simple-local-avatars'); ?></label></th>
 89             <td style="width: 50px;" valign="top">
 90                 <?php echo get_avatar( $profileuser->ID ); ?>
 91             </td>
 92             <td>
 93             <?php
 94                 $options = get_option('simple_local_avatars_caps');
 95 
 96                 if ( empty($options['simple_local_avatars_caps']) || current_user_can('upload_files') ) {
 97                     do_action( 'simple_local_avatar_notices' ); 
 98                     wp_nonce_field( 'simple_local_avatar_nonce', '_simple_local_avatar_nonce', false ); 
 99             ?>
100                     <input type="file" name="simple-local-avatar" id="simple-local-avatar" /><br />
101             <?php
102                     if ( empty( $profileuser->simple_local_avatar ) )
103                         echo '<span class="description">' . __('尚未设置本地头像,请点击“浏览”按钮上传本地头像。','simple-local-avatars') . '</span>';
104                     else 
105                         echo '
106                             <input type="checkbox" name="simple-local-avatar-erase" value="1" /> ' . __('移除本地头像','simple-local-avatars') . '<br />
107                             <span class="description">' . __('如需要修改本地头像,请重新上传新头像。如需要移除本地头像,请选中上方的“移除本地头像”复选框并更新个人资料即可。<br/>移除本地头像后,将恢复使用 Gravatar 头像。','simple-local-avatars') . '</span>
108                         ';      
109                 } else {
110                     if ( empty( $profileuser->simple_local_avatar ) )
111                         echo '<span class="description">' . __('尚未设置本地头像,请在 Gravatar.com 网站设置头像。','simple-local-avatars') . '</span>';
112                     else 
113                         echo '<span class="description">' . __('你没有头像上传权限,如需要修改本地头像,请联系站点管理员。','simple-local-avatars') . '</span>';
114                 }
115             ?>
116             </td>
117         </tr>
118     </table>
119     <script type="text/javascript">var form = document.getElementById('your-profile');form.encoding = 'multipart/form-data';form.setAttribute('enctype', 'multipart/form-data');</script>
120     <?php       
121     }
122 
123     public function edit_user_profile_update( $user_id ) {
124         if ( ! isset( $_POST['_simple_local_avatar_nonce'] ) || ! wp_verify_nonce( $_POST['_simple_local_avatar_nonce'], 'simple_local_avatar_nonce' ) )            //security
125             return;
126 
127         if ( ! empty( $_FILES['simple-local-avatar']['name'] ) ) {
128             $mimes = array(
129                 'jpg|jpeg|jpe' => 'image/jpeg',
130                 'gif' => 'image/gif',
131                 'png' => 'image/png',
132                 'bmp' => 'image/bmp',
133                 'tif|tiff' => 'image/tiff'
134             );
135 
136             // front end (theme my profile etc) support
137             if ( ! function_exists( 'wp_handle_upload' ) )
138                 require_once( ABSPATH . 'wp-admin/includes/file.php' );
139 
140             $this->avatar_delete( $user_id );   // delete old images if successful
141 
142             // need to be more secure since low privelege users can upload
143             if ( strstr( $_FILES['simple-local-avatar']['name'], '.php' ) )
144                 wp_die('For security reasons, the extension ".php" cannot be in your file name.');
145 
146             $this->user_id_being_edited = $user_id; // make user_id known to unique_filename_callback function
147             $avatar = wp_handle_upload( $_FILES['simple-local-avatar'], array( 'mimes' => $mimes, 'test_form' => false, 'unique_filename_callback' => array( $this, 'unique_filename_callback' ) ) );
148 
149             if ( empty($avatar['file']) ) {     // handle failures
150                 switch ( $avatar['error'] ) {
151                     case 'File type does not meet security guidelines. Try another.' :
152                         add_action( 'user_profile_update_errors', create_function('$a','$a->add("avatar_error",__("请上传有效的图片文件。","simple-local-avatars"));') );              
153                         break;
154                     default :
155                         add_action( 'user_profile_update_errors', create_function('$a','$a->add("avatar_error","<strong>".__("上传头像过程中出现以下错误:","simple-local-avatars")."</strong> ' . esc_attr( $avatar['error'] ) . '");') );
156                 }
157 
158                 return;
159             }
160 
161             update_user_meta( $user_id, 'simple_local_avatar', array( 'full' => $avatar['url'] ) );     // save user information (overwriting old)
162         } elseif ( ! empty( $_POST['simple-local-avatar-erase'] ) ) {
163             $this->avatar_delete( $user_id );
164         }
165     }
166 
167     /**
168      * remove the custom get_avatar hook for the default avatar list output on options-discussion.php
169      */
170     public function avatar_defaults( $avatar_defaults ) {
171         remove_action( 'get_avatar', array( $this, 'get_avatar' ) );
172         return $avatar_defaults;
173     }
174 
175     /**
176      * delete avatars based on user_id
177      */
178     public function avatar_delete( $user_id ) {
179         $old_avatars = get_user_meta( $user_id, 'simple_local_avatar', true );
180         $upload_path = wp_upload_dir();
181 
182         if ( is_array($old_avatars) ) {
183             foreach ($old_avatars as $old_avatar ) {
184                 $old_avatar_path = str_replace( $upload_path['baseurl'], $upload_path['basedir'], $old_avatar );
185                 @unlink( $old_avatar_path );    
186             }
187         }
188 
189         delete_user_meta( $user_id, 'simple_local_avatar' );
190     }
191 
192     public function unique_filename_callback( $dir, $name, $ext ) {
193         $user = get_user_by( 'id', (int) $this->user_id_being_edited ); 
194         $name = $base_name = sanitize_file_name( $user->user_login . '_avatar' );
195         $number = 1;
196 
197         while ( file_exists( $dir . "/$name$ext" ) ) {
198             $name = $base_name . '_' . $number;
199             $number++;
200         }
201 
202         return $name . $ext;
203     }
204 }
205 
206 $simple_local_avatars = new Simple_Local_Avatars;
207 
208 /**
209  * more efficient to call simple local avatar directly in theme and avoid gravatar setup
210  * 
211  * @param int|string|object $id_or_email A user ID,  email address, or comment object
212  * @param int $size Size of the avatar image
213  * @param string $default URL to a default image to use if no avatar is available
214  * @param string $alt Alternate text to use in image tag. Defaults to blank
215  * @return string <img> tag for the user's avatar
216  */
217 function get_simple_local_avatar( $id_or_email, $size = '96', $default = '', $alt = false ) {
218     global $simple_local_avatars;
219     $avatar = $simple_local_avatars->get_avatar( '', $id_or_email, $size, $default, $alt );
220 
221     if ( empty ( $avatar ) )
222         $avatar = get_avatar( $id_or_email, $size, $default, $alt );
223 
224     return $avatar;
225 }

缺点就是只能用本地图片上传,不支持媒体库中的图片。

posted @ 2022-10-20 09:32  lvtu  阅读(181)  评论(0)    收藏  举报