Quantcast
Channel: WordPress.org Forums » All Topics
Viewing all articles
Browse latest Browse all 59525

API – programmatically switch

$
0
0

Replies: 0

Hi, I have website, where I want switch user via php. I have some 50% solution like this



add_action( 'parse_query', 'test_parse_query' );
function test_parse_query( $wp_query ) {

    if ( isset( $wp_query->query['view-as-user'] ) && function_exists( 'view_admin_as' ) ) {
        if ( is_numeric( $wp_query->query['view-as-user'] ) ) {

            $request = array( 'user' => $wp_query->query['view-as-user'] );

            $view_admin_as = view_admin_as();

            //$view_admin_as->controller()->reset_view();

            $view_admin_as->store()->set_view( $view_admin_as->controller()->validate_view_data( $request ) );

            $data = $view_admin_as->controller()->validate_view_data( $view_admin_as->store()->get_view() );
            if ( $data ) {

                $meta = $view_admin_as->store()->get_userMeta( 'views' );
                // Make sure it is an array (no array means no valid data so we can safely clear it).
                if ( ! is_array( $meta ) ) {
                    $meta = array();
                }
                // Add the new view metadata and expiration date.
                $meta[ $view_admin_as->store()->get_curUserSession() ] = array(
                    'view' => $data,
                    'expire' => ( time() + (int) 86400 ),
                );
                // Update metadata (returns: true on success, false on failure).
                $view_admin_as->store()->update_userMeta( $meta, 'views', true );
            }

            wp_redirect( home_url( trailingslashit( _x( 'my-account', 'link my account', 'test' ) ) ) );
            die();
        }
    }

It work ok, but if user dont have cap “view_admin_as” and “edit_users”, it is not possible (https://github.com/JoryHogeveen/view-admin-as/wiki/Custom-capabilities). It is possible some workaround for switching user without these caps? Or can I use some filter for temporary adding them and remove after switching? Thank you for your help!

  • This topic was modified 28 minutes ago by Hrohh.

Viewing all articles
Browse latest Browse all 59525

Trending Articles