Sponsored Links

Showing posts with label wordpress. Show all posts
Showing posts with label wordpress. Show all posts

December 5, 2017

Automatically join any group when new user registers in Buddypress


function auto_join_group($user_id, $group_id) {
    if( !$user_id ) return false;

    // Join user to group with group id $group_id
    groups_accept_invite( $user_id, $group_id);
}

add_action( 'bp_core_activated_user', 'auto_join_group' );

Useful Buddypress Functions

bp_loggedin_user_id() = Get logged in user id
bp_displayed_user_id() = Get id of displayed user
bp_core_get_username($user_id) = Get username for the given id

Programmatically login user in wordpress

/**
 * Programmatically logs a user in
 *
 * @param string $username
 * @return bool True if the login was successful; false if it wasn't
 */
function programmatic_login( $username ) {
   // if user is already logged in then first log out
    if ( is_user_logged_in() ) {
        wp_logout();
    }

    add_filter( 'authenticate', 'allow_programmatic_login', 10, 3 );
    $user = wp_signon( array( 'user_login' => $username ) );
    remove_filter( 'authenticate', 'allow_programmatic_login', 10, 3 );
 
    if ( $user instanceof WP_User ) {
        wp_set_current_user( $user->ID, $user->user_login );

        if ( is_user_logged_in() ) {
            return true;
        }
    }

    return false;
}

/**
 * An 'authenticate' filter callback that authenticates the user using only the username.
 *
 * To avoid potential security vulnerabilities, this should only be used in the context of a programmatic login,
 * and unhooked immediately after it fires.
 *
 * @param WP_User $user
 * @param string $username
 * @param string $password
 * @return bool|WP_User a WP_User object if the username matched an existing user, or false if it didn't
 */
function allow_programmatic_login( $user, $username, $password ) {
    return get_user_by( 'login', $username );
}