Change User Avatar Programmatically in Wordpress

前端 未结 3 1684
说谎
说谎 2021-01-14 00:55

Is it possible to change the user avatar in WordPress programmatically? I\'m asking because I\'m facing a problem right now in displaying the user avatar in WordPress multis

相关标签:
3条回答
  • 2021-01-14 01:07

    I had to do three things to be able to programmatically insert user avatars into my WordPress starting with an avatar that is hosted at a remote URL.

    1. Install the WP User Avatar plugin.
    2. Borrow an upload function from WooCommerce. See below.
    3. Adapt some code from a similar support post

    Suppose you have a user whose avatar is $avatar_url = 'http://cdn.sstatic.net/stackoverflow/img/apple-touch-icon@2.png?v=73d79a89bded&a';

    I use the upload_product_image() from WooCommerce's class-wc-api-products.php to get the avatar into my local server.

    Then, using some of the code from this support post, create an attachment. Then associate the attachment with the user.

    This works only with the WP User Avatar plugin.

    function se13911452_set_avatar_url($avatar_url, $user_id) {
            global $wpdb;
            $file = upload_product_image($avatar_url);
            $wp_filetype = wp_check_filetype($file['file']);
            $attachment = array(
                'guid' => $file['url'],
                'post_mime_type' => $wp_filetype['type'],
                'post_title' => preg_replace('/\.[^.]+$/', '', basename($file['file'])),
                'post_content' => '',
                'post_status' => 'inherit'
            );
            $attach_id = wp_insert_attachment($attachment, $file['file']);
            $attach_data = wp_generate_attachment_metadata($attach_id, $file['file']);
            wp_update_attachment_metadata($attach_id, $attach_data);
            update_user_meta($user_id, $wpdb->get_blog_prefix() . 'user_avatar', $attach_id);
        }
    

    From WooCommerce's class-wc-api-products.php

    /**
     * WooCommerce class-wc-api-products.php
     * See https://github.com/justinshreve/woocommerce/blob/master/includes/api/class-wc-api-products.php
     * Upload image from URL
     *
     * @since 2.2
     * @param string $image_url
     * @return int|WP_Error attachment id
     */
    function upload_product_image($image_url) {
        $file_name = basename(current(explode('?', $image_url)));
        $wp_filetype = wp_check_filetype($file_name, null);
        $parsed_url = @parse_url($image_url);
    
        // Check parsed URL
        if(!$parsed_url || !is_array($parsed_url)) {
            throw new WC_API_Exception('woocommerce_api_invalid_product_image', sprintf(__('Invalid URL %s', 'woocommerce'), $image_url), 400);
        }
    
        // Ensure url is valid
        $image_url = str_replace(' ', '%20', $image_url);
    
        // Get the file
        $response = wp_safe_remote_get($image_url, array(
            'timeout' => 10
        ));
    
        if(is_wp_error($response) || 200 !== wp_remote_retrieve_response_code($response)) {
            throw new WC_API_Exception('woocommerce_api_invalid_remote_product_image', sprintf(__('Error getting remote image %s', 'woocommerce'), $image_url), 400);
        }
    
        // Ensure we have a file name and type
        if(!$wp_filetype['type']) {
            $headers = wp_remote_retrieve_headers($response);
            if(isset($headers['content-disposition']) && strstr($headers['content-disposition'], 'filename=')) {
                $disposition = end(explode('filename=', $headers['content-disposition']));
                $disposition = sanitize_file_name($disposition);
                $file_name = $disposition;
            }
            elseif(isset($headers['content-type']) && strstr($headers['content-type'], 'image/')) {
                $file_name = 'image.' . str_replace('image/', '', $headers['content-type']);
            }
            unset($headers);
        }
    
        // Upload the file
        $upload = wp_upload_bits($file_name, '', wp_remote_retrieve_body($response));
    
        if($upload['error']) {
            throw new WC_API_Exception('woocommerce_api_product_image_upload_error', $upload['error'], 400);
        }
    
        // Get filesize
        $filesize = filesize($upload['file']);
    
        if(0 == $filesize) {
            @unlink($upload['file']);
            unset($upload);
            throw new WC_API_Exception('woocommerce_api_product_image_upload_file_error', __('Zero size file downloaded', 'woocommerce'), 400);
        }
    
        unset($response);
    
        return $upload;
    }
    
    0 讨论(0)
  • 2021-01-14 01:11

    Most likely somewhere the get_avatar filter is being called and doing something. I recommend searching your plugins and themes for get_avatar and looking at things that look like: add_filter ('get_avatar', .....

    Otherwise, you can write your own behavior with the code below.

    <?php // in a plugin file or in a theme functions.php
    function SO13911452_override_avatar ($avatar_html, $id_or_email, $size, $default, $alt) {
        // check all values
    
        return $avatar_html
    }
    add_filter ('get_avatar', 'SO13911452_override_avatar', 10, 5);
    
    0 讨论(0)
  • 2021-01-14 01:14

    This will works :

    add_filter('get_avatar_data', 'ht1_change_avatar', 100, 2);
    
    function ht1_change_avatar($args, $id_or_email) {
        if($id_or_email == 1) {
            $args['url'] = 'https://uinames.com/api/photos/female/1.jpg';
        }
    
        if($id_or_email == 2) {
            $args['url'] = 'https://uinames.com/api/photos/male/19.jpg';
        }
    
        return $args;
    } // end of function
    

    If you have avatar dir location metas for users, then use this for all users :

    add_filter('get_avatar_data', 'ht1_change_avatar', 100, 2);
    
    function ht1_change_avatar($args, $id_or_email) {
        $avatar_url = get_user_meta($id_or_email, 'avatar', true);
    
        $args['url'] = $avatar_url;
    
        return $args;
    } // end of function
    

    Hope you get the point.

    0 讨论(0)
提交回复
热议问题