首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >过滤‘获取头像’对我不起作用

过滤‘获取头像’对我不起作用
EN

Stack Overflow用户
提问于 2014-04-03 17:37:37
回答 1查看 2.2K关注 0票数 1

我正在学习如何使用wordpress api进行开发。我想要显示我自己的头像,所以我正在点击“获取头像”过滤器。

这是我目前的代码...

代码语言:javascript
复制
function set_profile_avatar($id='', $size = "96", $default = '', $alt = 'profile avatar', $avatar_class = 'profile-avatar'  ) {

    echo $id;

    //get current user id
    global $current_user; 
    if(!$id){ $id = $current_user->ID; }

    //set the default avatar img
    $default= get_bloginfo('template_directory').'/images/default.png';

    //check to see if user has set custom avatar
    $gravatar_pic_url = get_user_meta($id, 'display_pic_url', true);

    if(!$gravatar_pic_url){
            $gravatar_pic_url = $default;
        }   

    //return the complied img tag
    return ("<img src='$gravatar_pic_url' width='$size' height='$size' class='$avatar_class' alt='$alt' />");
}

add_filter('get_avatar', 'set_profile_avatar'); 

我像这样调用函数...

代码语言:javascript
复制
<?php echo get_avatar($pending_member->ID, '150'); ?>

我在回调函数中回显了$id,我发现里面有一个生成的img标记。为什么我的ID变量没有传递给函数。

我猜我搞乱了过滤器钩子的工作方式。

EN

回答 1

Stack Overflow用户

发布于 2014-04-03 20:59:28

我发现了问题所在。add_filter钩子似乎将原始函数的输出作为第一个参数传递,所以即使您不打算使用它,也必须捕获它。

这就是现在运行的代码

代码语言:javascript
复制
//filter for profile avatar pic
function set_profile_avatar($content, $id='', $size = '96', $avatar_class = 'profile-avatar', $default = '', $alt = 'profile avatar') {

    //get current user id
    global $current_user; 
    if(!$id){ $id = $current_user->ID; }

    //set the default avatar img
    $default= get_bloginfo('template_directory').'/images/default.png';

    //check to see if user has set custom avatar
    $gravatar_pic_url = get_user_meta($id, 'display_pic_url', true);

    if(!$gravatar_pic_url){
            $gravatar_pic_url = $default;
        }   

    //return the complied img tag
    return ("<img src='$gravatar_pic_url' width='$size' height='$size' class='$avatar_class' alt='$alt' />");
}

add_filter('get_avatar', 'set_profile_avatar', 10, 5); 

现在,当我像这样调用get头像函数时...

代码语言:javascript
复制
<?php echo get_avatar($pending_member->ID, '150'); ?>

它将返回该配置文件ID的自定义头像。您必须考虑到原始函数的输出会自动作为第一个参数传递。

我希望这能为其他开发人员节省很多时间。

票数 3
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/22833576

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档