programing

워드프레스에서 프로그래밍 방식으로 사용자 아바타 변경

iphone6s 2023. 10. 19. 22:07
반응형

워드프레스에서 프로그래밍 방식으로 사용자 아바타 변경

워드프레스에서 사용자 아바타를 프로그래밍 방식으로 변경할 수 있습니까?워드프레스 다중 사이트에서 사용자 아바타를 표시하는 데 문제가 있어서 문의드립니다: 아바타가 표시되지 않습니다.

원격 URL에서 호스팅되는 아바타를 시작으로 사용자 아바타를 내 워드프레스에 프로그램적으로 삽입할 수 있도록 하기 위해서는 세 가지 작업을 해야 했습니다.

  1. WP User Avatar 플러그인을 설치합니다.
  2. WooCommerce에서 업로드 기능을 빌립니다.아래 참조.
  3. 유사한 지원 게시물의 일부 코드 수정

아바타가 다음과 같은 사용자가 있다고 가정해 보겠습니다.$avatar_url = 'http://cdn.sstatic.net/stackoverflow/img/apple-touch-icon@2.png?v=73d79a89bded&a';

사용합니다.upload_product_image()WooCommerce's에서class-wc-api-products.php아바타를 내 지역 서버로 보낼 수 있을 겁니다

그런 다음 이 지원 게시물의 코드 일부를 사용하여 첨부 파일을 만듭니다.그런 다음 첨부 파일을 사용자와 연결합니다.

이것은 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의 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;
}

작동합니다.

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

사용자를 위한 아바타 dir 위치 메타가 있는 경우, 모든 사용자를 위해 다음을 사용합니다.

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

요점을 이해하길 바랍니다.

아마도 어딘가에서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);

먼저 사용자 프로필에 author_pic meta를 추가합니다.

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

언급URL : https://stackoverflow.com/questions/13911452/change-user-avatar-programmatically-in-wordpress

반응형