Pardon me if this is ultrabasic, I'm fairly green to all this.
I'm trying to fetch a string value (chapter name) from a wordpress database, use a php function to rename the value and then concatenate the renamed value with some other variables to create a member_id.
Below is my current code (added to functions.php file) and I have 2 problems with it:
- From the 1st function, when I use the shortcode
[member_chapter]
in a page/post I always getPG
no matter what value of chapter name was used to register. If I switch the order of the foreach statements, then I always getBB
, i.e. I always get the return value of the firstif
statement no matter what chapter name is actually in the database. - From the 2nd function I never get the chapter_id, instead the result is always like
FAL--2020-1007
, i.e. it doesn't add the chapter_id value generated from the 1st function
I'd really appreciate any help.
/**
* Fetch chapter name and return as 2-character chapter_id
* Create shortcode for viewing chapter_id
*/
add_action('user_register', 'fetch_chapter');
function fetch_chapter(){
$current_user = wp_get_current_user();
$current_user_id = $current_user->ID;
global $wpdb;
$result = $wpdb->get_results('SELECT meta_value FROM usermeta WHERE meta_key = \'chapter_name\' AND user_id = ' . $current_user->ID);
foreach($result as $row){
if ($row->meta_value = 'Peregrine') {
return $row->meta_value = 'PG';
}elseif ($row->meta_value = 'Barbary') {
return $row->meta_value = 'BB';
}else {
return $row->meta_value;
}
}
}
add_shortcode('member_chapter', 'fetch_chapter');
/**
* Generate unique_id
* Retrieve chapter_id
* Create member_id
* Add member_id to user_meta table
*/
add_action('user_register', 'generate_member_id');
function generate_member_id($user_id){
$unique_id = 1000 + $user_id;
$chapter_id = fetch_chapter();
$member_id = "FAL-" . $chapter_id . "-" . date("Y") . "-" . $unique_id;
update_user_meta($user_id, 'member_id', $member_id);
}
Revised snippet
add_action('user_register', 'fetch_chapter');
function fetch_chapter(){
$current_user = wp_get_current_user();
$current_user_id = $current_user->ID;
global $wpdb;
$result = $wpdb->get_results('SELECT meta_value FROM usermeta WHERE meta_key = \'chapter_name\' AND user_id = '. $current_user->ID .' LIMIT 1');
if ($result[0]->meta_value == 'Peregrine') {
$result[0]->meta_value = 'PG';
}elseif ($result[0]->meta_value == 'Barbary') {
$result[0]->meta_value = 'BB';
}
return $result[0]->meta_value;
}
add_action('user_register', 'generate_member_id');
function generate_member_id($user_id){
$unique_id = 1000 + get_current_user_id();
$chapter_id = fetch_chapter();
$member_id = "FAL-" . $chapter_id . "-" . date("Y") . "-" . $unique_id;
return $member_id;
}
add_shortcode('member_id', 'generate_member_id');