Last active
October 12, 2021 19:15
-
-
Save wpexplorer/5aaa487132e2080efd801f8cb6e5d42e to your computer and use it in GitHub Desktop.
custom user avatar
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?php | |
namespace WPExplorer\Avatars; | |
defined( 'ABSPATH' ) || exit; | |
class Self_Hosted { | |
public function __construct() { | |
add_filter( 'user_contactmethods', array( $this, 'add_option' ) ); | |
add_filter( 'pre_get_avatar', array( $this, 'alter_avatar' ), 1 , 3 ); | |
} | |
public function add_option( $methods ) { | |
$methods['user_avatar'] = 'WPExplorer - Author Avatar'; | |
return $methods; | |
} | |
public function alter_avatar( $avatar, $id_or_email, $args ) { | |
$user_id = null; | |
if ( is_numeric( $id_or_email ) ) { | |
$user_id = $id_or_email; | |
} else { | |
if ( is_object( $id_or_email ) && 'WP_Comment' == get_class( $id_or_email ) ) { | |
$id_or_email = $id_or_email->comment_author_email; | |
} | |
if ( is_email( $id_or_email ) ) { | |
$user = get_user_by( 'email', $id_or_email ); | |
if ( $user && is_object( $user ) ) { | |
$user_id = $user->ID; | |
} | |
} | |
} | |
if ( $user_id ) { | |
$avatar_url = $this->get_local_avatar_url( $user_id ); | |
if ( ! empty( $avatar_url ) ) { | |
if ( empty( $user ) ) { | |
$user = get_user_by( 'id', $user_id ); | |
} | |
$custom_avatar_html = $this->avatar_html( $avatar_url, $user, $args ); | |
if ( $custom_avatar_html ) { | |
return $custom_avatar_html; | |
} | |
} | |
} | |
return $avatar; | |
} | |
public function get_local_avatar_url( $user_id = 0 ) { | |
$avatar_url = get_the_author_meta( 'user_avatar', $user_id ); | |
if ( is_numeric( $avatar_url ) ) { | |
$avatar_url = wp_get_attachment_url( $avatar_url ); | |
} | |
return $avatar_url; | |
} | |
public function avatar_html( $avatar = '', $user = '', $args = array() ) { | |
$size = isset( $args['size'] ) ? absint( $args['size'] ) : 50; | |
$class = 'avatar photo'; | |
if ( ! empty( $args['class' ] ) ) { | |
$class .= ' ' . esc_attr( $args['class'] ); | |
} | |
return '<img src="' . esc_url( $avatar ) . '" class="' . esc_attr( $class ) . '" alt="' . esc_attr( $user->display_name ) . ' Avatar" height="' . esc_attr( $size ) . '" width="' . esc_attr( $size ) . '" loading="lazy" />'; | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment