【问题标题】:Change User Avatar Programmatically in Wordpress在 Wordpress 中以编程方式更改用户头像
【发布时间】:2012-12-17 09:30:43
【问题描述】:

是否可以通过编程方式更改 WordPress 中的用户头像?我之所以问,是因为我现在在 WordPress 多站点中显示用户头像时遇到问题:头像未显示。

【问题讨论】:

  • 您能提供更多信息吗?你使用默认的内置 gravatar 吗?他们没有在哪里显示?运行什么代码来显示它们?
  • 是的,我在 wordpress 中使用默认的内置 gravatar。它们没有显示在用户在主博客中创建的新站点(博客)上。我使用 get_avatar() 进行显示。
  • 你可以试试这个wordpress.org/support/topic/…

标签: wordpress


【解决方案1】:

我必须做三件事才能以编程方式将用户头像插入到我的 WordPress 中,从托管在远程 URL 的头像开始。

  1. 安装WP User Avatar 插件。
  2. 从 WooCommerce 借用上传功能。见下文。
  3. 改编一些类似support post的代码

假设你有一个头像是$avatar_url = 'http://cdn.sstatic.net/stackoverflow/img/apple-touch-icon@2.png?v=73d79a89bded&a';的用户

我使用 WooCommerce 的 class-wc-api-products.php 中的 upload_product_image() 将头像导入我的本地服务器。

然后,使用此support post 中的一些代码,创建一个附件。 然后将附件与用户关联。

这仅适用于 WP User Avatar 插件。

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);
    }

来自WooCommerce'sclass-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;
}

【讨论】:

    【解决方案2】:

    get_avatar 过滤器很可能在某处被调用并执行某些操作。我建议在你的插件和主题中搜索 get_avatar 并查看如下内容:add_filter ('get_avatar', .....

    否则,您可以使用下面的代码编写自己的行为。

    <?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);
    

    【讨论】:

    • 太棒了,这正是我在开发带有配置文件小部件的自定义插件时所需要的。因此,我将用户头像 URL 保存到自定义元中,并在您指出的过滤器功能中读取它。谢谢!
    【解决方案3】:

    这将有效:

    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
    

    如果您有用户的头像目录位置元数据,则将其用于所有用户:

    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
    

    希望你明白这一点。

    【讨论】:

      【解决方案4】:

      首先将 author_pic 元数据添加到用户个人资料中:

      update_usermeta( $user_id, 'author_pic', trim($_POST['author_pic']) );
      

      并将这个过滤器添加到模板函数中:

      add_filter('get_avatar_data', 'ow_change_avatar', 100, 2);
      function ow_change_avatar($args, $user_data) {
          if(is_object($user_data)){
              $user_id = $user_data->user_id;
          } else{
              $user_id = $user_data;  
          }
          if($user_id){
              $author_pic = get_user_meta($user_id, 'author_pic', true);
              if($author_pic){
                  $args['url'] = $author_pic;
              } else {
                  $args['url'] = 'registerd user default img url';
              }
          } else {
              $args['url'] = 'guast user img url';
          }
          return $args;
      } 
      

      【讨论】:

        猜你喜欢
        • 2023-03-24
        • 2018-06-06
        • 2022-01-17
        • 2011-04-18
        • 2021-01-14
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多