I have an front-end ajax login on my site. I want to set the redirect url to '/services/clientarea';
for every page that is not part of the blog. For blog pages i want the login redirect to be $_SERVER['REQUEST_URI'];
Here is the code that I’m using which isn’t working for me:
function ajax_login_init(){
wp_register_script('ajax-login-script', get_template_directory_uri() . '/library/js/ajax-login-script.js', array('jquery') );
wp_enqueue_script('ajax-login-script');
global $post;
$posttype = get_post_type($post);
if ($posttype == 'post') {
$loginredirect = $_SERVER['REQUEST_URI'];
} else {
$loginredirect="/services/clientarea";
}
wp_localize_script( 'ajax-login-script', 'ajax_login_object', array(
'ajaxurl' => admin_url( 'admin-ajax.php' ),
'redirecturl' => $loginredirect,
'loadingmessage' => __('Signing in, please wait...')
));
// Enable the user with no privileges to run ajax_login() in AJAX
add_action( 'wp_ajax_nopriv_ajaxlogin', 'ajax_login' );
}
// Execute the action only if the user isn't logged in
if (!is_user_logged_in()) {
add_action('init', 'ajax_login_init');
}
It seems that the post type isn’t loaded in the init hook. Is there any way to identify it?
OK, let’s get some thing staight first.
Here is list of actions run during typical request. It goes like this:
- …
- init
- …
- parse_request
- …
- parse_query
- pre_get_posts
- posts_selection
- …
- wp
As you can see, posts are selected much later after init. To be more precise, even the request is parsed after init hook. So there is no easy way to get $post
in init
action, I’m afraid.
If you move your code from init
to wp
(or later), then you can get $post
from $wp_query
object.
But… I’m not sure if I understand, what are you trying to achieve with this code. If you hook your AJAX action based on queried post, it won’t fire up at all, I guess. Why? AJAX call is another request (/wp-admin/admin-ajax.php
) so there won’t be any $post
retrieved in this request, so your action won’t get hooked, so it won’t fire up.
I’m pretty sure this is what you really want:
function enqueue_ajax_login_scripts() {
wp_register_script('ajax-login-script', get_template_directory_uri() . '/library/js/ajax-login-script.js', array('jquery') );
wp_enqueue_script('ajax-login-script');
// check if it's single post
if ( is_singular('post') ) {
$loginredirect = $_SERVER['REQUEST_URI'];
} else {
$loginredirect="/services/clientarea";
}
wp_localize_script( 'ajax-login-script', 'ajax_login_object', array(
'ajaxurl' => admin_url( 'admin-ajax.php' ),
'redirecturl' => $loginredirect,
'loadingmessage' => __('Signing in, please wait...')
));
}
add_action('wp_enqueue_scripts', 'enqueue_ajax_login_scripts');
// it can be registered every time (it won't fire up unless there will be such AJAX request
add_action( 'wp_ajax_nopriv_ajaxlogin', 'ajax_login' );