I have a simple plugin I’ve created that performs some additional checks after a person has logged in to determine if they are allowed to access the site. It uses the wp_login hook to do so.
That functionality is working fine: we run our check and if they are not allowed to access the site, we call wp_logout().
But if they are denied access, I redirect them (wp_redirect) back to the registration/login page and want to inject a message on screen informing them why they are not allowed access. But I’m having a very difficult time figuring out a way to do that.
I’ve tried enqueuing a script (wp_enqueue_script) after the redirection. I’ve also tried injecting an inline script via the wp_footer hook. But nothing is working out. I think the problem is that I don’t have the ability to impact the page I’m being redirected to (even though the script doesn’t exit after wp_redirect unless I explicitly do so).
What is the best way to handle this post-redirect js injection? (I want to handle this with js/jquery so I can target the element where I want to insert the message.)
2 Answers
I figured out a solution that ended up being along the lines of the suggestions offered (though it felt like more work than I should have had to do just to inject some js on the page).
- I appended a variable to my redirection url:
wp_safe_redirect(esc_url(add_query_arg(‘failed_authentication’, ‘1’, ‘/register’))); - I registered the parameter variable using:
add_query_vars_filter($vars) - I registered a function with the wp_footer hook. Inside that function I retrieved the variable — get_query_var(‘failed_authentication’) — and printed my js/jQuery to inject the message (conditioned on that var).