When to load auto-login code?

时间:2012-01-03 作者:getWeberForStackExchange

我正在使用此(简化)代码通过单点登录系统的插件自动登录用户:

$user_info = get_userdatabylogin( $username );
$user_id = $user_info->ID;
wp_set_current_user( $user_id );
wp_set_auth_cookie( $user_id );
do_action( \'wp_login\', $username );
我在网上找到的许多代码片段将此代码绑定到init 行动使用时init, 我在页面上加载元素的时间安排上遇到了一些问题。例如,当Log In 元链接更改为Logout 在第一个。似乎在设置用户会话之前加载了一些元素。

我应该何时加载此代码?正在查看http://codex.wordpress.org/Plugin_API/Action_Reference, plugins\\u加载的最佳时间是?

谢谢,迈克

1 个回复
最合适的回答,由SO网友:getWeberForStackExchange 整理而成

我最终使用了来自的“plugins\\u-loaded”操作或状态http://codex.wordpress.org/Plugin_API/Action_Reference:

在我的主插件文件中,我有:

include_once( \'lib/class-my-auth.php\' ); // your class file here
add_action( \'plugins_loaded\', \'My_Auth::auto_login\' );
在lib/class中我的身份验证。php:

<?php

class My_Auth {

    private static $successfully_connected_Main_to_WP = false;

    public static function auto_login() {

            $username = ...; // Integrate with main site to get username from active session

            // Check if WP user is logged in
            if ( is_user_logged_in() ) {

                // Get current WP user
                $current_wp_user = wp_get_current_user();

                // Logout if the current WP user is different than the main site user
                if ( strToLower( $username ) !== strToLower( $curren_wp_user->user_login ) ) {
                    self::logout_of_wp();
                } else {
                    self::$successfully_connected_Main_to_WP = true;
                }

            }

            // If a connection b/w main site & WP has not been established, login if possible
            if ( ! self::$successfully_connected_Main_to_WP && $user_info = get_userdatabylogin($username) ) {

                $user_id = $user_info->ID;

                if ( $user_id > 0 ) {
                    wp_set_auth_cookie( $user_id );
                    wp_set_current_user( $user_id );
                    self::$successfully_connected_Main_to_WP = true;
                }

            }

        }

        // If no connection b/w main site & WP was established, and the user is
        // logged in, logout.
        if ( ! self::$successfully_connected_Main_to_WP && is_user_logged_in() ) {
            self::logout_of_wp();
        }

    }

    private static function logout_of_wp() {

        // Clear the auth cookie, and do other stuff
        wp_clear_auth_cookie();
        do_action(\'wp_logout\');

        // Unset the current user
        wp_set_current_user(0);

    }

}

结束

相关推荐

将目录路径传递给plugins_url()安全吗?

plugins_url() 函数接受插件slug或文件路径来构建URL。我有以下目录结构:/wp-content/mu-plugins/someplugin/css/file.css /wp-content/mu-plugins/someplugin/includes/file.php 我需要建立URL到file.css 在里面file.php. 我不能通过__FILE__ 因为这将是一个层次太深。plugins_url(\'css/file.css\', __FILE__ )