I've created a custom field in user profile where upload a profile image. It's very simple.
To create fields I've used:
add_action( 'show_user_profile', 'cover_image_function' );
add_action( 'edit_user_profile', 'cover_image_function' );
function cover_image_function( $user )
{
<h3>Cover Image</h3>
<style type="text/css">
.fh-profile-upload-options th,
.fh-profile-upload-options td,
.fh-profile-upload-options input {
vertical-align: top;
}
.user-preview-image {
display: block;
height: auto;
width: 300px;
}
</style>
<table class="form-table fh-profile-upload-options">
<tr>
<th>
<label for="image">Cover Image</label>
</th>
<td>
<img class="user-preview-image" src="<?php echo esc_attr( get_the_author_meta( 'mycoverimage', $user->ID ) ); ?>">
<input type="text" name="mycoverimage" id="mycoverimage" value="<?php echo esc_attr( get_the_author_meta( 'mycoverimage', $user->ID ) ); ?>" class="regular-text" />
<input type='button' class="button-primary" value="Upload Image" id="coverimage"/><br />
<span class="description">Please upload your cover image.</span>
</td>
</tr>
</table>
<script type="text/javascript">
(function( $ ) {
$( 'input#coverimage' ).on('click', function() {
tb_show('', 'media-upload.php?type=image&TB_iframe=true');
window.send_to_editor = function( html )
{
imgurl = $( 'img', html ).attr( 'src' );
$( '#mycoverimage' ).val(imgurl);
tb_remove();
}
return false;
});
})(jQuery);
</script>
}
To save my image:
add_action( 'personal_options_update', 'save_cover_image' );
add_action( 'edit_user_profile_update', 'save_cover_image' );
function save_cover_image( $user_id ) {
if ( !current_user_can( 'edit_user', $user_id ) )
{
return false;
}
update_user_meta( $user_id, 'mycoverimage', $_POST[ 'mycoverimage' ] );
}
Everything works fine but I can't retrieve the attachment ID
for generating the thumbnails and smaller sizes. For now I can just get the url like:
echo esc_attr( get_the_author_meta( 'mycoverimage', $user->ID ) );
I've even used the known method like in other questions:
function get_attachment_id($image_url) {
global $wpdb;
$attachment = $wpdb->get_col($wpdb->prepare("SELECT ID FROM $wpdb->posts WHERE guid='%s';", $image_url ));
return $attachment[0];
}
But It doesn't work. Is it possible that the image doesn't generate any attachment metadata, while uploading? And how Can I do it? Even suggestions, articles or questions already answered would be appreciated. Everything but a plugin, I want build a custom code. Thanks!