如何在这种情况下将字符串添加到函数中?

时间:2015-03-15 19:07:45

标签: javascript php buddypress

我正在尝试将一些功能添加到插件调用buddypress first-letter-avatar中。它根据用户名的第一个字母分配头像,但是,我想自定义它。我希望它也基于usename的性别。我想在以下函数中添加一个字符串$ gender,我试图在这段代码中添加$ gender,以什么方式实现,或者我应该在哪里查看这段代码并开始自定义呢?升值。

<?php
private function choose_custom_avatar($username, $size, $alt = '', $gender){
		$id=//get user_id, dont know how to get it yet
		$gender=bp_get_profile_field_data('Gender', $id);//

		// get picture filename (and lowercase it) from commenter name:
		//var_dump($username);
		$file_name = substr($username, $this->letter_index, 1); // get one letter counting from letter_index
		$file_name = strtolower($file_name); // lowercase it...
		// if, for some reason, the result is empty, set file_name to default unknown image:
		if (empty($file_name)){
			$file_name = $this->image_unknown;
		}

		// create array with allowed character range (in this case it is a-z range):
		$allowed_chars = range('a', 'z');
		
		// check if the file name meets the requirement; if it doesn't - set it to unknown
		if (!in_array($file_name, $allowed_chars)){
			$file_name = $this->image_unknown;
		}
		
		
		
		// detect most appropriate size based on WP avatar size:
		if ($size <= 48 && $gender=='Female') $custom_avatar_size = '48';
		else if ($size > 48 && $size <= 96 && $gender=='Female') $custom_avatar_size = '96';
		else if ($size > 96 && $size <= 128 && $gender=='Female') $custom_avatar_size = '128';
		else if ($size > 128 && $size <= 256 && $gender=='Female') $custom_avatar_size = '256';
		else if ($size <= 48 && $gender=='Male') $custom_avatar_size = '1';
		else if ($size > 48 && $size <= 96 && $gender=='Male') $custom_avatar_size = '2';
		else if ($size > 96 && $size <= 128 && $gender=='Male') $custom_avatar_size = '3';
		else if ($size > 128 && $size <= 256 && $gender=='Male') $custom_avatar_size = '4';
		else $custom_avatar_size = '512';
	

		// create file path - avatar_path variable will look something like this:
		// http://yourblog.com/wp-content/plugins/wp-first-letter-avatar/images/default/96/k.png):
		$avatar_uri =
			plugins_url() . '/'
			. dirname(plugin_basename(__FILE__)) . '/'
			. self::BPFLA_IMAGES_PATH . '/'
			. $this->avatar_set . '/'
			. $custom_avatar_size . '/'
			. $file_name . '.'
			. $this->images_format;

		// output the final HTML img code:
		return $this->output_img($avatar_uri, $size, $alt);
	}
	


?>

1 个答案:

答案 0 :(得分:1)

在我看来,你试图将$gender变量作为参数传递给函数,然后在第3行,你在函数中定义了这个变量:

private function choose_custom_avatar($username, $size, $alt = '', $gender){
        $id=//get user_id, dont know how to get it yet
        $gender=bp_get_profile_field_data('Gender', $id);//

这不是这样做的方法。相反,传递一个变量,比如$gen作为参数,然后根据是否传递性别参数,重新定义函数中的$gender变量:

private function choose_custom_avatar($username, $size, $alt = '', $gen=null){
        $id=//get user_id, dont know how to get it yet
        $gen !== '' ? $gender = $gen : $gender=bp_get_profile_field_data('Gender', $id);

这样,您不必更改代码,如果未传递$gen参数,它将像以前一样工作。