Custom size for image uploaded to custom field in user profile?

Your first problem is that custom field is saved as url, and not as id. So you need to retrieve the attachment id from the url. First tentation is to use the ‘guid’ field.

Resist the temptation and find another way: for robust wordpress code you have to think ‘guid’ not exists, so repeat with me: “guid does not exist”.

Once ‘guid’ does not exists we have to find another way, this good one, come from here

function get_logo_id_from_url( $attachment_url="" ) {
    global $wpdb;
    $attachment_id = false;
    if ( '' == $attachment_url ) return;
    $upload_dir_paths = wp_upload_dir();
    if ( false !== strpos( $attachment_url, $upload_dir_paths['baseurl'] ) ) {
     $attachment_url = preg_replace('/-\d+x\d+(?=\.(jpg|jpeg|png|gif)$)/i','',$attachment_url);
     $attachment_url = str_replace($upload_dir_paths['baseurl']."https://wordpress.stackexchange.com/",'',$attachment_url);
     $attachment_id = $wpdb->get_var( $wpdb->prepare(
       "SELECT wposts.ID FROM $wpdb->posts wposts, $wpdb->postmeta wpostmeta 
       WHERE wposts.ID = wpostmeta.post_id AND
       wpostmeta.meta_key = '_wp_attached_file' AND
       wpostmeta.meta_value="https://wordpress.stackexchange.com/questions/89199/%s" AND
       wposts.post_type="attachment"", $attachment_url ) );
    }
    return $attachment_id;
  }

Then we use previous function to wrire another one:

 function author_logo( $author_id = 0, $size="", $alt="" ) {
   if ( ! intval($author_id) ) return;
   $author_logo = get_field('author_logo' , 'user_' . $author_id );
   if ( filter_var($author_logo, FILTER_VALIDATE_URL) ) return;
   if ( empty($size) ) {
      $nosize = true;
   } else {
      $logo_id = get_logo_id_from_url( $author_logo );
      if ( ! intval($logo_id) ) {
         $nosize = true;
      } else {
        $sizedlogo = wp_get_attachment_image_src(logo_id, $size);
        $nosize = filter_var($sizedlogo[0], FILTER_VALIDATE_URL) ? false : true;
      }
   }
   if ( $nosize ) {
     return sprintf('<img src="https://wordpress.stackexchange.com/questions/89199/%s" alt="https://wordpress.stackexchange.com/questions/89199/%s" />', $author_logo, $alt );
   } else {
     return sprintf('<img src="https://wordpress.stackexchange.com/questions/89199/%s" alt="https://wordpress.stackexchange.com/questions/89199/%s" />', $sizedlogo[0], $alt );
   }
 }

After you saved these function in a plugin or in theme functions.php you can use them in this way:

<?php

// print default size
echo author_logo( $author_id ); 

// print in a custom size
echo author_logo( $author_id, 'homepage-thumb' );

// print in a custom size with custom alt text
echo author_logo( $author_id, 'homepage-thumb', 'Author Logo' ); 

?>

Code is untested but should works, unless any typo…

Leave a Comment