WordPress 给评论框添加男女选项,并根据选项显示自定义的男女头像

LMS
1.3K+ 16

首先是题外话:

折腾主题的时候遇到一个遇见鬼的问题,同样一个主题,用的是自定义的 comment_form() 函数来调用评论框,可在不同的电脑上,文本框和用户名、Email、网址的输入框居然位置不一样,在办公室电脑里【用户名、Email、网址的输入框】是显示在【评论内容文本框】的上面,而家里的电脑上却是【评论内容文本框】在【用户名、Email、网址的输入框】的上面,让我百思不得其姐……

百度是不用想的,Goole 打不开,只好用 global.bing.com 了,也不知道用什么英文搜索关键字,只能漫无目的的找了,然后就找到老外一个关于给评论框添加男女选项,并根据选项显示自定义的男女头像的文章,感觉挺有意思的,对于不想使用 gavatar 又不想搞复杂用户系统上传头像的童鞋,可以试试。

首先,通过函数在 comment form 里插入男、女选项

// Add the actions to show gender field on comment form 
add_action( 'comment_form_logged_in_after', 'wti_additional_comment_field' ); 
add_action( 'comment_form_after_fields', 'wti_additional_comment_field' ); 
function wti_additional_comment_field() { 
    echo '<p class="comment-form-gender">'. '<label for="gender_male">性别 </label>'.
         '<input id="gender_male" name="gender" type="radio" value="male" checked="checked" /> 男'.
         '<input id="gender_female" name="gender" type="radio" value="female" /> 女</p>'; 
}

然后,提交评论的时候将性别数据保存到 comment_id 对应的 comment_meta 里

// Add the action to save the gender in comment 
add_action( 'comment_post', 'wti_save_comment_meta_data' ); 
function wti_save_comment_meta_data( $comment_id ) { 
    $gender = wp_filter_nohtml_kses( $_POST['gender'] ); 
    add_comment_meta( $comment_id, 'gender', $gender );
}

最后,让默认头像函数显示男、女不同性别的头像

// Add the filter to have custom avatar 
add_filter('get_avatar', 'wti_custom_avatar', 10, 5); 
function wti_custom_avatar($avatar, $id_or_email, $size, $default, $alt) {
  global $comment; 
  if ( is_object ( $comment ) && !empty ( $comment ) ) { 
    // Remove to avoid recursion 
    remove_filter( 'get_avatar', 'wti_custom_avatar' ); 
    // Get the comment id and gender for that comment 
    $comment_id = get_comment_ID(); 
    $gender = get_comment_meta( $comment_id, 'gender', true ); 
    // Assign the image url as per gender 
    if ( $gender == 'female' ) { 
      $default = 'default_female_avatar_url'; 
    } else { 
      $default = 'default_male_avatar_url'; 
    } 
    // Get the avatar with default url 
    $avatar = get_avatar( $comment, $size, $default ); 
    // Add the filter again 
    add_filter( 'get_avatar', 'wti_custom_avatar', 10, 5 ); 
  } 
  return $avatar; 
}

上面函数里,需要自己将默认的男、女头像地址替换对应的 default_female_avatar_urldefault_male_avatar_url,且默认显示男性性别头像。

原文地址见这里:http://www.webtechideas.in/how-to-show-gender-based-custom-avatar-in-wordpress-comments/

好吧,转载完了,可我的问题还是没解决,怎么会遇到这么见鬼的问题呢,谁来帮我啊啊啊啊。。。。。。

THE END

评论 16

    1. 让无头像的游客可以选自己的头像,不过可选的不多,只区分男女。

    1. 个人博客用处不大,不过如果用wp做企业站,留言系统就能用的上了,显示个指定的头像总比默认的好看些,不过也算强迫症的一种吧。

  1. 那个主题还精简着吗?嘿嘿嘿~~~

    1. 我说我现在用的这个主题就是那个主题改的结果你还想要么?

      1. 啥? 我真没看出来,cms样式也都给删了吗? :???:
        我那个头像不显示问题,有线索吗?

        1. 只要不使用用户系统,把用用户id调用头像改成email调用就好了。

  2. 默认的comment_form从4.4开始把留言框框挪到身份上面了.你是不是用了什么缓存插件?

    1. 没有装什么插件,现在怀疑是不是两个本地环境 php 版本不同的问题。

    2. 哈哈哈,想起来了,真是脑袋有坑了, 是wp版本的问题,公司这边环境的wp没升级还是4.3。。。。

  3. 给你的折腾能力跪了……

发表评论

Submit