In wordpress, there is no in-built functionality for assigning gender to users. Also there is no such functionality on the comment form. So we need to add custom code to achieve this functionality as per the steps given below.

  • Add the gender field in the comment form.
  • Save the gender as meta data of that comment.
  • Change the get avatar functionality of the comment to pass the default url as per gender.

Let’s add the gender field first.

// 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">' . __( 'Gender' ) . '</label>'.
'<input id="gender_male" name="gender" type="radio" value="male" checked="checked" /> ' . __( 'Male' ) .
'<input id="gender_female" name="gender" type="radio" value="female" />' . __( 'Female' ) .

Let’s save the gender value as comment meta data.

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

Modify the get avatar functionality to use default image url so that we can pass custom url as per 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;

Few things to note:
– Gender is set to male as default.
– You need to replace the default_female_avatar_url and default_male_avatar_url values with yours.

That’s it. Happy coding 🙂

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.