当我使用wp_reDirect()函数时,也可能会重定向

时间:2017-09-29 作者:lomse

我想我的插件重定向到一个页面时,一些条件不符合插件激活后。我一直在To many redirects... 错误消息。

我的代码如下所示:

if (! defined(\'WPINC\')) die;
if (! class_exists(\'AwesomePlugin\')) {

    class AwesomePlugin {
        public function __construct(){
            //Register admin menus
            add_action(\'admin_menu\', [$this, add_menu]);

            //Init plugin
            add_action(\'admin_init\', [$this, \'init_plugin\']);
        }

        /**
         *
         * Init plugin
         */
        public function init_plugin(){
            if(!isset(get_option("some_option"))){
                wp_redirect("admin.php?page=some-page"); exit; //This gives too many redirects
            }
            wp_redirect(\'admin.php?page=dashboard\'); exit;
        }

        /**
         * Add menu and submenu items 
         */
        public function add_menu(){
            add_menu_page( 
                \'Dashboard\', \'Dashboard\', \'manage_options\', \'dashboard\', 
                [__CLASS__, \'load_dashboard_view\'], 
                plugins_url(\'logo.png\', __FILE__)
            );

            add_submenu_page(
                \'\', \'Signup page\', \'Signup page\', \'manage_options\', 
                \'sign-up\', [__CLASS__, \'load_signup_view\']
            ); 
        }  

        /**
         * Dashboard page 
         */
        public function load_dashboard_view(){
            include(plugin_dir_path(__FILE__) . \'dashboard.php\');
        } 

        /**
         * Signup page
         */
        public function load_signup_view(){
            include(plugin_dir_path(__FILE__) . \'signup.php\');
        }           
    } 

    AwesomePlugin()   
}
我错过了什么?

EDIT: 我知道无论我加载的页面是什么init_plugin 功能持续启动。因此,它会不断将用户重定向到sign-up, 因此many redirect 错误消息。如何解决此问题?

1 个回复
SO网友:Shakeeb Ahmed

这将帮助您实现您想要实现的目标。

// Add option
register_activation_hook( __FILE__, \'me_shakeeb_install\' );
function me_shakeeb_install() {

    $result = \'signup\'; // Perform your logic here to decide where to redirect
    add_option( \'me_shakeeb_redirect_to\', $result );
}

// Check Option
add_action( \'init\', \'me_shakeeb_signup_check\' );
function me_shakeeb_signup_check() {

    /**
     * Redirect to about page.
     */
    if ( false !== get_option( \'me_shakeeb_redirect_to\', false ) ) {
        $page = get_option( \'me_shakeeb_redirect_to\', false );
        delete_option( \'me_shakeeb_redirect_to\' );
        wp_redirect( admin_url( \'admin.php?page=$page\' ) );
        exit;
    }
}

结束

相关推荐