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' );