0

Am creating a WordPress site whereby am enabling users to upload their own custom profile images from a custom form. Once they upload am storing the image URL in a database table and the image is then stored inside the WordPress wp-content/uploads folder. This works fine

enter image description here

When a user logs in, I want to show the uploaded image as an avatar in wordpress dashboard at the top-right corner as shown below. Ideally it should be Welcome test [avatar-image]

enter image description here

Updated code using get_avatar filter hook, now it works

add_filter( 'get_avatar', 'my_custom_avatar', 10, 6 );
function my_custom_avatar( $avatar, $id_or_email, $size, $default, $alt, $args ) {
    
    // Get the user by ID or by email
    $user = false;
    if ( is_numeric( $id_or_email ) ) {
        $user = get_user_by( 'id', (int)$id_or_email );
    } else {
        $user = get_user_by( 'email', $id_or_email );    
    }
    // print_r( $user ); // exit();

    if ( $user && is_object( $user ) ) {

        // You need something here to get your user's custom image.
        // Your example is using a custom db table, so you'll need to work
        // out you query to get the right value for the right user ID.
        //Queried profile_details table
        global $wpdb;

        $sql = "SELECT * FROM profile_details WHERE user_id = " . $user->ID;
        // echo $sql; // exit();

        $query_result = $wpdb->get_results( $sql);
        
        //Finally able to get the avatarUrl
    $avatar_url = $query_result[0]->avatarUrl;
        
        if ( $avatar_url ) {
        
            // HTML for the avatar <img> tag.  This is WP default.
            $avatar = sprintf(
                "<img alt='%s' src='%s' class='%s' height='%d' width='%d' %s/>",
                esc_attr( $alt ),
                esc_url( $avatar_url ),
                esc_attr( "avatar avatar-" . $size . " photo" ),                
                (int) $args['height'],
                (int) $args['width'],
                $args['extra_attr']
            );
        }
    }
    
    //print_r( $avatar);
    return $avatar;
}

I go ahead to display the avatar from the front-end template(header.php) using the code below

<?php
       global $current_user;
       get_currentuserinfo();
       echo get_avatar( $current_user->ID, 48 );
?>

The weird thing is instead of the custom avatar showing am getting the default gravatar.

enter image description here

When I print_r($avatar) from my_custom_avatar filter method, I get the actual avatar that was uploaded printed

enter image description here

Not understanding why it picks the default gravatar when I use get_avatar() method instead of picking the avatar image loaded from the filter ?

2 Answers 2

0

If you're trying to get an avatar for a specific user, you probably shouldn't be using get_the_author_meta() - I'm not sure why you would use that (perhaps you got part of this from another snippet?).

get_avatar() can get the user's avatar by either ID or email. If the user is logged in, their ID is readily available from get_current_user_id(), so you should probably use that to get the user's id like so:

$menu_item->title =  'Welcome' . ' ' . get_avatar( get_current_user_id(), 'medium' );

That doesn't necessarily mean it will solve your problem. It will correct the issue of attempting to get the avatar, but your question is somewhat incomplete. Are you doing something to filter the get_avatar() result to use your custom image? If not, you're going to also need to do something similar to the following. Note that I've commented a section that you'll need to work out the details of because you're using a custom table (or it appears that you are from your image screenshot) with the user's image file you want to use. You'll need to be able to query the db to get that value in the section I noted:

add_filter( 'get_avatar', 'my_custom_avatar', 10, 6 );
function my_custom_avatar( $avatar, $id_or_email, $size, $default, $alt, $args ) {
    
    // Get the user by ID or by email
    $user = false;
    if ( is_numeric( $id_or_email ) ) {
        $user = get_user_by( 'id', (int)$id_or_email );
    } else {
        $user = get_user_by( 'email', $id_or_email );    
    }
    // print_r( $user ); // exit();

    if ( $user && is_object( $user ) ) {

        // You need something here to get your user's custom image.
        // Your example is using a custom db table, so you'll need to work
        // out you query to get the right value for the right user ID.
        //Queried profile_details table
        global $wpdb;

        $sql = "SELECT * FROM profile_details WHERE user_id = " . $user->ID;
        // echo $sql; // exit();

        $query_result = $wpdb->get_results( $sql);
        // print_r( $query_result ); // exit();

        $avatar_url = $query_result->avatarUrl;
        // print_r( $avatar_url ); // exit();
        
        if ( $avatar_url ) {
        
            // HTML for the avatar <img> tag.  This is WP default.
            $avatar = sprintf(
                "<img alt='%s' src='%s' class='%s' height='%d' width='%d' %s/>",
                esc_attr( $alt ),
                esc_url( $avatar_url ),
                esc_attr( "avatar avatar-" . $size . " photo" ),                
                (int) $args['height'],
                (int) $args['width'],
                $args['extra_attr']
            );
        }
    }
    return $avatar;
}

UPDATE

I updated the code based on your notes/query. (StackExchange is a Q&A format, not a regular forum, so don't post your update as an answer unless it's a different answer from any others)

There are a number of possibilities, so I put possible breakpoints where I would suggest outputting var contents to debug. Use exit() if necessary, but keep in mind that this filter fires any time the avatar is loaded - including for you, so you'll want to have the test page already loaded.

Here are some notes on the possible problems:

  1. The $user object is not loaded based on the passed info (user ID). To removed the possibility of checking it as an object. That possibility is almost nil and was in the original code snippet I had used for a similar custom avatar. I don't think you need it, so I took that out. There's a commented out breakpoint so the first thing to check is whether you're getting a valid user object.
  2. Check if the query is valid. I separated the query so you can check that. I took the user object out and concatenated it instead.
  3. If things check out good so far, then check the results of the query.
6
  • @buttlerblog, Thanks a lot, I have followed your advice bit still does not work. Please check the new answer I just posted.
    – Pweb
    Dec 29, 2022 at 17:51
  • @buttlerblog .. Please bear with me, am new to WordPress hooks, and I might have made some mistakes in the code I posted. Please assist in editing
    – Pweb
    Dec 29, 2022 at 18:02
  • I updated the answer with code changes and notes on troubleshooting it.
    – butlerblog
    Dec 30, 2022 at 12:26
  • @buttlerblog ,, Thanks a lot, your suggestions were very helpful. The avatarUrl is now picking well from custom table. But another weird error has cropped up. When I use the get_avatar() method to display the avatar in header.php template, the default gravatar is displayed. When I print_r the avatar from the custom filter method, the custom avatar picked from db displays. Seems the get_avatar() is not able to pick the custom avatar. I have updated the code wit the new errors that am getting. Please check.
    – Pweb
    Dec 30, 2022 at 13:31
  • Try SELECT * FROM {$wpdb->prefix}profile_details ...
    – shanebp
    Dec 30, 2022 at 19:51
-1
// Função para adicionar upload de avatar no perfil do usuário para administradores e editores
function custom_user_avatar_field( $profileuser ) {
  $user = wp_get_current_user();
  if ( ! in_array( 'administrator', $user->roles ) && ! in_array( 'editor', $user->roles ) ) {
      // Se o usuário não for administrador ou editor, saia
      return;
  }

  if ( function_exists( 'is_bbpress' ) && is_bbpress() ) {
      // Se for uma página do bbPress, saia
      return;
  }
  ?>
  
      input[type="file"] {
          display: none;
      }
      .upload-avatar {
          border: 1px solid #ccc;
          display: inline-block;
          padding: 6px 12px 3px 6px;
          cursor: pointer;
          margin-bottom: 10px;
          border-radius: 4px;
          /*background-image: url();*/
          background-color: #f2f2f2;
          background-repeat: repeat;
          text-decoration: none !important;
          color: #777;
          margin-top: 10px;
          margin-right: 20px;
      }
      #avatar {
          border: 1px solid #ddd;
          border-radius: 4px;
      }
  
  
: ID ); ?> roles; if ( in_array( 'administrator', $current_user_roles ) || in_array( 'editor', $current_user_roles ) ) { // Se o usuário for administrador ou editor, exiba o campo de upload de avatar $options = get_option( 'custom_user_avatars_caps' ); if ( empty( $options['custom_user_avatars_caps'] ) || current_user_can( 'upload_files' ) ) { // Nonce segurança wp_nonce_field( 'custom_user_avatar_nonce', '_custom_user_avatar_nonce', false ); // Entrada de upload de arquivo echo ' ' . esc_html__( 'Enviar Foto', 'text-domain' ) . ' '; if ( empty( $profileuser->custom_user_avatar ) ) { echo '' . esc_html__( 'Nenhuma foto foi definida, clique no botão Enviar Foto para adicionar uma nova.', 'text-domain' ) . '

'; } else { echo '

' . esc_html__( 'Deletar foto atual', 'text-domain' ) . '

'; echo '' . esc_html__( 'Substitua a foto enviando uma nova ou apague a atual marcando a opção Deletar foto atual.', 'text-domain' ) . '

'; } } else { if ( empty( $profileuser->custom_user_avatar ) ) { echo '' . esc_html__( 'Nenhuma foto foi definida. Configure uma imagem padrão em www.gravatar.com', 'text-domain' ) . '

'; } else { echo '' . esc_html__( 'Você não tem permissões de gerenciamento de mídia. Para alterar sua foto local, entre em contato com o administrador do site.', 'text-domain' ) . '

'; } } } ?> var form = document.getElementById('your-profile'); form.encoding = 'multipart/form-data'; form.setAttribute('enctype', 'multipart/form-data'); // Salvar a imagem do avatar no perfil do usuário function custom_user_avatar_field_save( $user_id ) { // Verificar nonce if ( ! isset( $_POST['_custom_user_avatar_nonce'] ) || ! wp_verify_nonce( $_POST['_custom_user_avatar_nonce'], 'custom_user_avatar_nonce' ) ) { return; }

if ( ! empty( $_FILES['custom-user-avatar']['name'] ) ) { // Extensões/tipos de arquivo permitidos $mimes = array( 'jpg|jpeg|jpe' => 'image/jpeg', 'gif' => 'image/gif', 'png' => 'image/png', );

  // Fazer o upload da imagem
  $upload_overrides = array( 'test_form' => false );
  $movefile = wp_handle_upload( $_FILES['custom-user-avatar'], $upload_overrides );

  // Verificar se o upload foi bem sucedido
  if ( $movefile && ! isset( $movefile['error'] ) ) {
      $avatar_url = $movefile['url'];

      // Salvar o URL da imagem do avatar no perfil do usuário
      update_user_meta( $user_id, 'custom_user_avatar', $avatar_url );
  }

} elseif ( ! empty( $_POST['custom-user-avatar-erase'] ) ) { // Deletar o avatar delete_user_meta( $user_id, 'custom_user_avatar' ); } }

// Adicionar campos de upload de avatar no perfil do usuário add_action( 'show_user_profile', 'custom_user_avatar_field' ); add_action( 'edit_user_profile', 'custom_user_avatar_field' );

// Salvar imagem do avatar no perfil do usuário add_action( 'personal_options_update', 'custom_user_avatar_field_save' ); add_action( 'edit_user_profile_update', 'custom_user_avatar_field_save' );

// Exibir o avatar no perfil do usuário function display_custom_user_avatar( $avatar, $id_or_email, $size, $default, $alt ) { if ( is_numeric( $id_or_email ) ) { $user_id = $id_or_email; } elseif ( is_object( $id_or_email ) ) { if ( isset( $id_or_email->user_id ) ) { $user_id = $id_or_email->user_id; } else { return $avatar; } } else { $user = get_user_by( 'email', $id_or_email ); if ( ! $user ) { return $avatar; } $user_id = $user->ID; }

// Verificar se o usuário tem uma imagem personalizada de avatar $custom_avatar = get_user_meta( $user_id, 'custom_user_avatar', true );

if ( $custom_avatar ) { // Exibir o avatar personalizado $avatar = ""; }

return $avatar; } add_filter( 'get_avatar', 'display_custom_user_avatar', 10, 5 );

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.