代码之家  ›  专栏  ›  技术社区  ›  Swen

写入数据库,并在相同的PHP页面加载中检索更新的数据?

  •  1
  • Swen  · 技术社区  · 6 年前

    1. 用户创建帐户,立即登录并显示主页。
    2. 一个函数检查数据库以查看帐户是否已激活,如果没有,则在主页上显示一条消息,要求单击验证电子邮件中的链接。
    3. https://example.com/?action=activate&user=swen&key=1234 )
    4. 打开此页时,函数将检查 action 参数已设置并运行帐户激活函数,然后将帐户更新为“已激活”。
    5. WP的其余部分被执行,但是检查帐户激活的功能仍然显示帐户尚未激活。
    6. https://example.com 同样,如果没有查询变量,则消息将消失,这表明上面的示例URL实际上起到了激活帐户的作用。

    将数据写入数据库和检索相同的更新数据之间的时间是否可能太短?


    更新:

    不知道MySQL是否将数据缓存在同一个页面加载中。我尝试在检索更新的用户角色之前刷新WordPress缓存,没有成功。

    检查URL并运行 activate_user 功能:

    setup_theme 挂钩以确保在加载主题之前运行。

    add_action('setup_theme', 'ns_activate_user_action');
    function ns_activate_user_action() {
        // Check if all action parameters are present
        if ( !ns_validate_action('activate', array('user', 'key')) ) {
            return;
        }
    
        // Activate user by key, runs the "activate_user" function
        $activate_user = activate_user_by_key($_GET['user'], $_GET['key']);
    
        // At this point the user role should have changed
        // and the account be activated
    }
    

    function activate_user($user) {
        // ...
    
        $user->add_role( 'member' );
        $user->remove_role( 'member_pending' );
    
        // ...
    
        return $user;       
    }
    

    检查帐户是否激活的功能:

    function is_user_activated($user) {
    
        // ...
    
        if ( in_array( 'member_pending', (array) $user->roles ) ) {
            return false;
        }
    
        return true;
    }
    

    do_action() 在主题文件中:

    add_action('ns_after_header', 'ns_activate_account_notice_front_page');
    function ns_activate_account_notice_front_page() {
        if ( is_user_logged_in() && is_front_page() && !is_user_activated() ) {
            // ... Echos message asking user to click activation link in email
            // Checking the user role here with wp_get_current_user()->roles
            // still shows that the user is in the "member_pending" role (inactive)
        }
    }
    
    2 回复  |  直到 6 年前
        1
  •  0
  •   Jamie_D    6 年前

    我会尝试在add_动作的优先顺序上游刃有余。由于您没有在add_action函数中指定它们,因此它们都默认为十(10)。

    https://developer.wordpress.org/reference/functions/add_action/

    这似乎是他们的完美用例

        2
  •  0
  •   Swen    6 年前

    所以事实证明,这是WordPress的问题,很可能与cache有关。看看这个问题 这是为了得到更多的信息。

    Updated user role inncorrect when using wp_get_current_user()

    是的,您可以写入数据库,并在相同的PHP页面加载中检索更新的信息。