check if member is of a group - wordpress

I use buddypress with multiple groups. Every user can also join multiple groups as a member. I use custom profile fields for e.g. the address. Every member can select, who is able to view his profile. This try is based on the plugin 'User Profile Visibility Manager'. Now I need an additional option: View the profile to "Group Members Only"
My plan is:
Get the user_id of the 'visitor' - works perfect with:
$user_id_visitor = bp_loggedin_user_id();
Get the user_id of the 'profile owner' - works perfect with:
$user_id_profile_owner = bp_displayed_user_id();
Get the group(s) by the profile owner´s user_id:
Here, I´ve tried a lot. With this function, I´m able to print all groups in which the 'profile owner' is a member. But I don´t need to print it, it is only for a test:
function bp_groups_profileowner( $user_id_profile_owner ) {
global $wpdb;
$groups = $wpdb->get_results( $wpdb->prepare( "SELECT group_id FROM wp_bp_groups_members WHERE user_id = %d", $user_id_profile_owner ) );
if ( $groups ) {
foreach ( $groups as $group ) {
echo '<li>' . $group->group_id . '</li>';
}
}
check all members of the profile_owner´s group(s) and check, if the visitor is also member the group(s).
My new option in the selectbox:
<option value="groupmembers" <?php echo selected('groupmembers',bp_profile_visibility_get_settings($user_id,'bp_profile_visibility' ));?>><?php _e('Group Members Only','bp-profile-visibility');?></option>
This is the code snippet, coming from the plugin, which checks and protects user account visibility:
/**
* Checks and protects user account visibility
* #return type
*/
function check_profile_access(){
if(!bp_is_user() || is_super_admin())
return;
//if we are on user profile page
$privacy = bp_profile_visibility_get_settings(bp_displayed_user_id(), 'bp_profile_visibility');
//if privacy is public, everyone can see
if( 'public' == $privacy )
return;
$referrer=wp_get_referer();
if($referrer)
$referrer=bp_core_get_root_domain ();
//in all other cases, user must be logged in
if(!is_user_logged_in()){
bp_core_add_message(__('Please login to view profile','bp-profile-visibility'),'error');
wp_safe_redirect($referrer);
exit(0);
return ;
}
//if we are here, the person is logged in, let us see if the visibility is set to logged in
if( 'loggedin' == $privacy )
return ;
//if this is my profile, do not prevent user
if(bp_is_my_profile())
return ;
//now, since we have already tested for login , we just need to test for the friends only and me
if( 'friends' == $privacy && function_exists('friends_check_friendship') && friends_check_friendship(bp_displayed_user_id(), get_current_user_id()) )
return;
//now, we just need to test for the group members
if( 'groupmembers' ... )
//if we are here, don't show the profile
bp_core_add_message(__('This User\'s privacy settings does not allow you to view the profile.','bp-profile-visibility'),'error');
wp_safe_redirect($referrer);
exit(0);
return ;
}

I found the solution by myself:
//now, we just need to test for the group members only and me
if( 'groupmembers' == $privacy )
/**
* Check if visitor is a member of one of the profile owners groups mm
*
*/
$user_id_visitor = bp_loggedin_user_id();
$user_id_profile_owner = bp_displayed_user_id();
$all_groups = BP_Groups_Member::get_group_ids( $user_id_profile_owner);
if ( $all_groups ) {
foreach($all_groups[groups] AS $profile_owner_groups_id)
{
if (groups_is_user_member( $user_id_visitor, $profile_owner_groups_id ))
// break if visitor is member of one of the profie owners group //
return;
}
}

Related

Changing Roles in WooC based on Order Status

I want to be able to manually confirm offers --> Thereby changing the order status before a user gets assigned a new role on my page. I tried to combine two functions I found here but when I launched them the page crashed.
The manual confirmation is important since we have to check each person that wants to purchase a membership. The Roles are important because I use them to limit access to other parts of the website.
A users Journey:
A user comes to the website. Then has to log in or create a profile. Then they are forwarded to the site where you can get the membership. (Woocomerce and Stripe) I want to be able to manually confirm if somebody buys a membership or not. If I confirm the user gets a new role. If I don't confirm the user gets no role or is deleted ( the payments should obviously not happen in that case.
What is the problem can somebody please help?
function uiwc_change_role( $order_id ) {
// get all the order data
$order = new WC_Order($order_id);
$user = $order->get_user();
$order_status = $order->get_status();
if ('complete' == $order_status) {
if( false != $user && !user_can($user, 'administrator') ){
// our new role name
$role = 'aktives_mitglied2022';
//set the new role to our customer
$user->set_role($role);
}
//return $order_status;
}
}
//add this newly created function to the thank you page
add_action( 'woocommerce_thankyou', 'uiwc_change_role', 100, 1 );
function custom_uiwc_change_role( $order_id ) {
// get all the order data
$order = new WC_Order($order_id);
$user = $order->get_user();
$order_status = $order->get_status();
if ('complete' == $order_status) {
if( false != $user && !user_can($user, 'administrator') ){
// our new role name
$role = 'aktives_mitglied2022';
//set the new role to our customer
$user->set_role($role);
}
//return $order_status;
}
}
//add this newly created function to the thank you page
add_action( 'woocommerce_thankyou', 'custom_uiwc_change_role', 100, 1 );

Woocommerce - Edit account issue

My Woocommerce is setup to generate username automatically. I'm trying to use the code below to change username before save. I would like to change user name to be equal a custom field filled in billing form.
My code is:
function wc_cpf_as_username ( $user_login ) {
if( !empty($_POST['billing_cpf'] ) ) {
$user_login = $_POST['billing_cpf'];
}
elseif (!empty( $_POST['billing_cnpj'] )){
$user_login = $_POST['billing_cnpj'];
}
else{
$user_login = $_POST['billing_email'];
}
return $user_login;
}
add_filter( 'pre_user_login' , 'wc_cpf_as_username' );
The code work to create user, but this code do not work to edit user in my account page (/my-account/edit-account). Woocommerce show success message (Account details changed successfully.), but data is not changed.
I do not know what is the issue.
Could you help me?
Why you are making that complex function if you have a hook available for this. edit_user_profile_update hook i.e. located in /wp-admin/user-edit.php.
update_user_meta($user_id, 'custom_meta_key', $_POST['custom_meta_key']).
update_user_meta thats for update user meta field based on user ID.
add_action('edit_user_profile_update', 'update_extra_profile_fields');
function update_extra_profile_fields($user_id) {
if ( current_user_can('edit_user',$user_id) )
update_user_meta($user_id, 'Custom_field', $_POST['your_field']);
}

Buddypress - when user activates account,user role changes to default

Iam working with buddypress,
I have a two user roles,
1-student
2-faculty
and i have set default user role as subscriber.
when user registers and activates account by clicking on link sent through mail.User role changes to default(subscriber).
Any idea what is the issue? Below is the code assigning role to user on sign up.
add_action('bp_core_signup_user', 'ad_user_signup_usermeta', 10, 5);
function ad_user_signup_usermeta($user_id, $user_login, $user_password, $user_email, $usermeta) {
if(isset($_POST['signup_membership']) && !empty($_POST['signup_membership']))
update_user_meta($user_id, 'membership', $_POST['signup_membership']);
$userdata = array();
$userdata['ID'] = $user_id;
if(!empty($_POST['signup_usertype'])) {
if($_POST['signup_usertype'] == 'student') {
$userdata['role'] = 'student';
}
if($_POST['signup_usertype'] == 'instructor') {
$userdata['role'] = 'instructor';
}
}
if ($userdata['role']){
wp_update_user($userdata);
}
}
Upon activation, BuddyPress (at least version 2.0.2) updates the user's role to the default role.
https://buddypress.trac.wordpress.org/browser/tags/2.0.2/bp-members/bp-members-functions.php#L1560
You can comment out that line, or write some code to work around it. I'm using "WP Roles At Registration" and ran across the same problem. I ended up adding a filter on bp_core_signup_user to save the original role but you'll want to add something like this to your ad_user_signup_usermeta:
update_user_meta($user_id, 'temp_role', $role_name)
then reset it back in a filter for bp_core_activated_user
public function after_bp_activated_user($user_id, $key, $user) {
$user = get_userdata($user_id);
$role = get_user_meta($user_id, 'temp_role');
if ($role) {
$user->set_role($role[0]);
}
}
add_filter('bp_core_activated_user', array($this, 'after_bp_activated_user'), 30, 3);

Nested relations in Drupal

I have a D7 website where users can make content (obviously...). So every node has it's own author. Every author is a member of an organization. But he can be a member of more then one organization. So far the facts.
I would like to create a view where the content is filtered on Author. Very easy, set the relation of the view on "Content's Author" and select the current user as filter.
But what I would like is to filter on the author's organization. So in fact it's a nested relation. Filter the nodes on the current logged in user (that's easy), but how can I filter on the current logged in user's organization?
Ok, the panels didn't work out, so I wrote my own hook :-)
function mymodule_views_pre_view (&$view, &$display_id, &$args) {
// Only execute this script when the view 'fiches_my_thema' is called
if ('fiches_my_thema' == $view->name) {
// Get users thema
global $user;
$userRoles = $user->roles;
$user_themas = array();
// Filter roles so you end up with the "Thema's".
foreach ($userRoles as $key) {
if(strpos($key,'edacteur')) {
$key = str_replace('Redacteur - ','', $key);
$key = str_replace('Eindredacteur - ','', $key);
$user_themas[] = $key;
}
}
// Resolve tid
$terms = taxonomy_get_tree(5);
$allRoles = array();
$arguments = array();
// Assign the 'tid' to a variable
foreach ($terms as $key) {
$singleRoles = $key->name;
$allRoles[] = $singleRoles;
if(in_array($singleRoles, $user_themas)) {
$arguments[] = $key->tid;
}
}
// Only when the arguments are NOT empty, set the arguments
if(!empty($arguments)) {
$finalArguments = implode("+", $arguments);
$args[] = "$finalArguments";
$view->set_arguments($args);
}
}
}

How can user 1 or super admin be excluded in search results in Drupal 7?

I'm looking for a way to exclude the admin user or user 1 from user search results in drupal 7.
I want this to not show up for security reasons.
If you build a custom search using Views, you can set the filter(s) to only show users with certain roles. Do not expose the filter to users. If User 1 has the "administrator" role and everyone else has another (non-administrator) role, when you apply the filter, only non-administrator accounts will show up when a search is run.
You can implement hook_preprocess_search_result() by inserting the following into template.php. Note you'll have to clear the Drupal cache to enable this function in Configuration -> Performance -> Clear Cache
function <themename>_preprocess_search_result(&$variables) {
global $language;
$display_result = true;
if( $variables['module'] == 'user' ) {
if( $variables['user']->uid == 1 || $variables['id'] == 1 ) {
$display_result = false;
$variables = array();
}
}
if( $display_result ) {
$result = $variables['result'];
$variables['url'] = check_url($result['link']);
$variables['title'] = check_plain($result['title']);
if (isset($result['language']) && $result['language'] != $language->language && $result['language'] != LANGUAGE_NONE) {
$variables['title_attributes_array']['xml:lang'] = $result['language'];
$variables['content_attributes_array']['xml:lang'] = $result['language'];
}
$info = array();
if (!empty($result['module'])) {
$info['module'] = check_plain($result['module']);
}
if (!empty($result['user'])) {
$info['user'] = $result['user'];
}
if (!empty($result['date'])) {
$info['date'] = format_date($result['date'], 'short');
}
if (isset($result['extra']) && is_array($result['extra'])) {
$info = array_merge($info, $result['extra']);
}
// Check for existence. User search does not include snippets.
$variables['snippet'] = isset($result['snippet']) ? $result['snippet'] : '';
// Provide separated and grouped meta information..
$variables['info_split'] = $info;
$variables['info'] = implode(' - ', $info);
$variables['theme_hook_suggestions'][] = 'search_result__' . $variables['module'];
}
}
Another way to do it would be search-result.tpl.php and check the $info_split array to check if the search result was user one and not display any output.
Don't forget that you'll need to also prevent users from visiting site.com/user/1 as they'll be able to get just as much information from this page.

Resources