【问题标题】:filtering 'get avatar' not working for me过滤“获取头像”对我不起作用
【发布时间】:2014-04-03 20:59:27
【问题描述】:

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

这是我目前的代码...

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

我这样调用函数...

<?php echo get_avatar($pending_member->ID, '150'); ?>

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

我猜我搞砸了过滤器挂钩的工作原理。

【问题讨论】:

  • 你没有设置参数:add_filter( filter, callback_func, priority, PARAMS )
  • 我改成add_filter('get_avatar', 'set_profile_avatar', 10, 5);还是不行。
  • 好的,乍一看它只是弹出。我记得我也有这个问题。 get_avatarpluggable function,也许值得一看。
  • "这个函数是可插入的,但是为了兼容性的目的,希望改变 gravatar 输出的插件作者应该使用 get_avatar 过滤器。"所以你是对的,但他们仍然建议使用过滤器。我只是找不到任何关于如何将参数正确传递给“过滤”函数的好例子

标签: php wordpress


【解决方案1】:

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

这是现在工作的代码

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

现在当我像这样调用获取头像函数时...

<?php echo get_avatar($pending_member->ID, '150'); ?>

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

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2023-02-02
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多