代码实现WordPress添加本地头像功能代替Gravatar头像

今天就来教大家使用代码将 Gravatar 头像半本地化,那么什么是半本地化呢?也就是通过用户的邮箱判断用户是…

今天就来教大家使用代码将 Gravatar 头像半本地化,那么什么是半本地化呢?也就是通过用户的邮箱判断用户是否拥有 Gravatar 头像,如果拥有则使用 Gravatar 头像,当用户拥有本地头像且拥有 Gravatar 头像时,则优先使用本地头像。

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

将以上代码加入到 functions.php 或者 functions.php 引入的 php 文件中即可实现 Gravatar 头像半本地化,最后来张效果图:

类别:WordPress教程

本文收集自互联网,转载请注明来源。
如有侵权,请联系 wper_net@163.com 删除。

评论 (0)COMMENT

登录 账号发表你的看法,还没有账号?立即免费 注册