Independent Publisher 2: Don't Show Gravatar if it's the Default Gravatar

* Uses caching to help lessen queries.
* Code forked from https://gist.github.com/justinph/5197810

Closes #145
This commit is contained in:
David A. Kennedy 2018-05-30 17:51:08 -04:00
parent ea7f7b3339
commit 3ac81407c4
2 changed files with 58 additions and 1 deletions

View file

@ -28,7 +28,7 @@
<div class="site-branding">
<?php the_custom_logo(); ?>
<?php if ( '' !== get_theme_mod( 'independent_publisher_2_gravatar_email', get_option( 'admin_email' ) ) ) : ?>
<?php if ( '' !== get_theme_mod( 'independent_publisher_2_gravatar_email', get_option( 'admin_email' ) ) && validate_gravatar( get_theme_mod( 'independent_publisher_2_gravatar_email', get_option( 'admin_email' ) ) ) ) : ?>
<a class="site-logo-link" href="<?php echo esc_url( home_url( '/' ) ); ?>">
<img alt="" class="site-logo-image no-grav" width="80" height="80" src="<?php echo esc_url( get_avatar_url( get_theme_mod( 'independent_publisher_2_gravatar_email', get_option( 'admin_email' ) ), array( 'size' => 160 ) ) ); ?>" />
</a><!-- .site-logo-link -->

View file

@ -67,3 +67,60 @@ function independent_publisher_2_pingback_header() {
}
}
add_action( 'wp_head', 'independent_publisher_2_pingback_header' );
/**
* Utility function to check if a gravatar exists for a given email or id
* @param int|string|object $id_or_email A user ID, email address, or comment object
* @return bool if the gravatar exists or not
* @link https://gist.github.com/justinph/5197810
*/
function validate_gravatar( $id_or_email ) {
// The id or email code is borrowed from wp-includes/pluggable.php.
$email = '';
if ( is_numeric( $id_or_email ) ) {
$id = (int) $id_or_email;
$user = get_userdata( $id );
if ( $user ) {
$email = $user->user_email;
}
} elseif ( is_object( $id_or_email ) ) {
// No avatar for pingbacks or trackbacks.
$allowed_comment_types = apply_filters( 'get_avatar_comment_types', array( 'comment' ) );
if ( ! empty( $id_or_email->comment_type ) && ! in_array( $id_or_email->comment_type, (array) $allowed_comment_types, true ) ) {
return false;
}
if ( ! empty( $id_or_email->user_id ) ) {
$id = (int) $id_or_email->user_id;
$user = get_userdata( $id );
if ( $user ) {
$email = $user->user_email;
}
} elseif ( ! empty( $id_or_email->comment_author_email ) ) {
$email = $id_or_email->comment_author_email;
}
} else {
$email = $id_or_email;
}
$hashkey = md5( strtolower( trim( $email ) ) );
$uri = 'http://www.gravatar.com/avatar/' . $hashkey . '?d=404';
$data = wp_cache_get( $hashkey );
$expire = 60 * 5;
$group = '';
if ( false === $data ) {
$response = wp_remote_head( $uri );
if ( is_wp_error( $response ) ) {
$data = 'not200';
} else {
$data = $response['response']['code'];
}
wp_cache_set( $hashkey, $data, $group, $expire );
}
if ( 200 === $data ) {
return true;
} else {
return false;
}
}