如何为WordPress添加本地头像功能替换掉Gravatar头像。

jerry wordpress 2015年08月09日 收藏
  1. <?phpclass 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', __('Local Avatar Permissions','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                    if ( empty( $profileuser->simple_local_avatar ) )
  102.                         echo '<span class="description">' . __('尚未设置本地头像,请点击“浏览”按钮上传本地头像。','simple-local-avatars') . '</span>';
  103.                     else
  104.                         echo '
  105.                             <input type="checkbox" name="simple-local-avatar-erase" value="1" /> ' . __('移除本地头像','simple-local-avatars') . '<br />
  106.                             <span class="description">' . __('如需要修改本地头像,请重新上传新头像。如需要移除本地头像,请选中上方的“移除本地头像”复选框并更新个人资料即可。<br/>移除本地头像后,将恢复使用 Gravatar 头像。','simple-local-avatars') . '</span>
  107.                         ';     
  108.                 } else {
  109.                     if ( empty( $profileuser->simple_local_avatar ) )
  110.                         echo '<span class="description">' . __('尚未设置本地头像,请在 Gravatar.com 网站设置头像。','simple-local-avatars') . '</span>';
  111.                     else
  112.                         echo '<span class="description">' . __('你没有头像上传全乡,如需要修改本地头像,请联系站点管理员。','simple-local-avatars') . '</span>';
  113.                 }
  114.             ?>
  115.             </td>
  116.         </tr>
  117.     </table>
  118.     <script type="text/javascript">var form = document.getElementById('your-profile');form.encoding = 'multipart/form-data';form.setAttribute('enctype', 'multipart/form-data');</script>
  119.     <?php       
  120.     }
  121.      
  122.     public function edit_user_profile_update( $user_id ) {
  123.         if ( ! isset( $_POST['_simple_local_avatar_nonce'] ) || ! wp_verify_nonce( $_POST['_simple_local_avatar_nonce'], 'simple_local_avatar_nonce' ) )            //security
  124.             return;
  125.      
  126.         if ( ! empty( $_FILES['simple-local-avatar']['name'] ) ) {
  127.             $mimes = array(
  128.                 'jpg|jpeg|jpe' => 'image/jpeg',
  129.                 'gif' => 'image/gif',
  130.                 'png' => 'image/png',
  131.                 'bmp' => 'image/bmp',
  132.                 'tif|tiff' => 'image/tiff'
  133.             );
  134.      
  135.             // front end (theme my profile etc) support
  136.             if ( ! function_exists( 'wp_handle_upload' ) )
  137.                 require_once( ABSPATH . 'wp-admin/includes/file.php' );
  138.      
  139.             $this->avatar_delete( $user_id );    // delete old images if successful
  140.      
  141.             // need to be more secure since low privelege users can upload
  142.             if ( strstr( $_FILES['simple-local-avatar']['name'], '.php' ) )
  143.                 wp_die('For security reasons, the extension ".php" cannot be in your file name.');
  144.      
  145.             $this->user_id_being_edited = $user_id; // make user_id known to unique_filename_callback function
  146.             $avatar = wp_handle_upload( $_FILES['simple-local-avatar'], array( 'mimes' => $mimes, 'test_form' => false, 'unique_filename_callback' => array( $this, 'unique_filename_callback' ) ) );
  147.      
  148.             if ( empty($avatar['file']) ) {     // handle failures
  149.                 switch ( $avatar['error'] ) {
  150.                     case 'File type does not meet security guidelines. Try another.' :
  151.                         add_action( 'user_profile_update_errors', create_function('$a','$a->add("avatar_error",__("请上传有效的图片文件。","simple-local-avatars"));') );              
  152.                         break;
  153.                     default :
  154.                         add_action( 'user_profile_update_errors', create_function('$a','$a->add("avatar_error","<strong>".__("上传头像过程中出现以下错误:","simple-local-avatars")."</strong> ' . esc_attr( $avatar['error'] ) . '");') );
  155.                 }
  156.      
  157.                 return;
  158.             }
  159.      
  160.             update_user_meta( $user_id, 'simple_local_avatar', array( 'full' => $avatar['url'] ) );      // save user information (overwriting old)
  161.         } elseif ( ! empty( $_POST['simple-local-avatar-erase'] ) ) {
  162.             $this->avatar_delete( $user_id );
  163.         }
  164.     }
  165.      
  166.     /**
  167.      * remove the custom get_avatar hook for the default avatar list output on options-discussion.php
  168.      */
  169.     public function avatar_defaults( $avatar_defaults ) {
  170.         remove_action( 'get_avatar', array( $this, 'get_avatar' ) );
  171.         return $avatar_defaults;
  172.     }
  173.      
  174.     /**
  175.      * delete avatars based on user_id
  176.      */
  177.     public function avatar_delete( $user_id ) {
  178.         $old_avatars = get_user_meta( $user_id, 'simple_local_avatar', true );
  179.         $upload_path = wp_upload_dir();
  180.      
  181.         if ( is_array($old_avatars) ) {
  182.             foreach ($old_avatars as $old_avatar ) {
  183.                 $old_avatar_path = str_replace( $upload_path['baseurl'], $upload_path['basedir'], $old_avatar );
  184.                 @unlink( $old_avatar_path );   
  185.             }
  186.         }
  187.      
  188.         delete_user_meta( $user_id, 'simple_local_avatar' );
  189.     }
  190.      
  191.     public function unique_filename_callback( $dir, $name, $ext ) {
  192.         $user = get_user_by( 'id', (int) $this->user_id_being_edited );
  193.         $name = $base_name = sanitize_file_name( $user->user_login . '_avatar' );
  194.         $number = 1;
  195.      
  196.         while ( file_exists( $dir . "/$name$ext" ) ) {
  197.             $name = $base_name . '_' . $number;
  198.             $number++;
  199.         }
  200.      
  201.         return $name . $ext;
  202.     }}
  203.      $simple_local_avatars = new Simple_Local_Avatars;
  204.      function get_simple_local_avatar( $id_or_email, $size = '96', $default = '', $alt = false ) {
  205.     global $simple_local_avatars;
  206.     $avatar = $simple_local_avatars->get_avatar( '', $id_or_email, $size, $default, $alt );
  207.      
  208.     if ( empty ( $avatar ) )
  209.         $avatar = get_avatar( $id_or_email, $size, $default, $alt );
  210.      
  211.     return $avatar;}

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

86441399780293.png