Skip to content

Instantly share code, notes, and snippets.

@rayrutjes
Created January 15, 2018 11:30
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save rayrutjes/b90c166ff518510a293b3566dca2e5b3 to your computer and use it in GitHub Desktop.
Save rayrutjes/b90c166ff518510a293b3566dca2e5b3 to your computer and use it in GitHub Desktop.
Custom avatar in Algolia plugin for WordPress
<?php
/**
* Plugin Name: Customize data pushed to Algolia.
*/
/**
* @param int $user_id
* @param string $fallback_avatar_url
*
* @return string
*/
function ca_get_user_avatar_url( $user_id, $fallback_avatar_url ) {
$user_id = (int) $user_id;
$avatar_override = get_user_option( 'metronet_avatar_override', $user_id );
if ( ! $avatar_override || $avatar_override != 'on' ) {
return $fallback_avatar_url;
}
$post_id = (int) get_user_option( 'metronet_post_id', $user_id );
$avatar_url = '';
$post_thumbnail_id = get_post_thumbnail_id( $post_id );
if ( $post_thumbnail_id ) {
$avatar_url = wp_get_attachment_thumb_url( $post_thumbnail_id );
}
if ( ! $avatar_url ) {
return $fallback_avatar_url;
}
return $avatar_url;
}
/**
* @param int $post_id
* @param string $post_thumbnail_fallback_url
*
* @return mixed
*/
function ca_get_post_thumbnail_url( $post_id, $post_thumbnail_fallback_url ) {
$post_id = (int) $post_id;
$thumbnail_id = get_post_thumbnail_id( $post_id );
if ( ! $thumbnail_id ) {
return $post_thumbnail_fallback_url;
}
$thumb = wp_get_attachment_image_src( get_post_thumbnail_id( $post_id ), 'main-block' );
if ( ! $thumb ) {
return $post_thumbnail_fallback_url;
}
return $thumb[0];
}
/**
* Push the overridden profile image provided by metronet-profile-picture plugin.
*
* @param array $record
* @param WP_User $user
*
* @return array
*/
function ca_algolia_user_record( array $record, WP_User $user ) {
$record['avatar_url'] = ca_get_user_avatar_url( $user->ID, $record['avatar_url'] );
return $record;
}
add_filter( 'algolia_user_record', 'ca_algolia_user_record', 10, 2 );
/**
* @param array $record
* @param WP_Post $post
*
* @return array
*/
function ca_algolia_post_shared_attributes( array $record, WP_Post $post ) {
$record['thumbnail_url'] = ca_get_post_thumbnail_url( $post->ID, $record['thumbnail_url'] );
$record['post_author']['display_name'] = ca_get_user_avatar_url( $record['post_author']['user_id'], get_avatar_url( $record['post_author']['user_id'] ) ) . '|' . $record['post_author']['display_name'];
$record['date_formatted'] = get_the_date( '', $post );
return $record;
}
add_filter( 'algolia_post_shared_attributes', 'ca_algolia_post_shared_attributes', 10, 2 );
add_filter( 'algolia_searchable_post_shared_attributes', 'ca_algolia_post_shared_attributes', 10, 2 );
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment