Why doesn't global $wp_query not get hooked?

I have a plugin that helps me to make lazy loading on posts of a custom post type. The idea is to add an action to the template_redirect/init and get data from the global $wp_query to make jquery understand how much loading there needs to be done.
The plugin php file looks like this:

function pbd_alp_init() {
   global $wp_query;

   // Add code to index pages.
   if( !is_singular() ) {   // can i select a specific post type here?
      wp_enqueue_script(
        'pbd-alp-load-posts',
        plugins_url( 'js/load-posts.js', __FILE__ ),
        array('jquery'),
        '1.0',
        true
      );

      // What page are we on? And what is the pages limit?
      $max = $wp_query-max_num_pages; // this returns 0
      $paged = ( get_query_var('paged')  1 ) ? get_query_var('paged') : 1;

      // Add some parameters for the JS.
      wp_localize_script(
        'pbd-alp-load-posts',
        'pbd_alp',
        array(
            'startPage' = $paged,
            'maxPages' = $max,
            'nextLink' = next_posts($max, false)
        )
      );
  }
}
add_action('init', 'pbd_alp_init');

Im sure that max_num_pages function returns a number when i call it directly - why does my global $wp_query seem to be empty?
In the documentation it says that the action should hook to the 'template_redirect' but 'init' seem to be more right? Both doesn't hook up to the wp_query..

Topic infinite-scroll php init hooks Wordpress

Category Web


If you look at the Action Reference, you can see the order things happen.

Note where init is, the query object doesn't exist until the wp action.

// ...
init
└─ widgets_init
register_sidebar
wp_register_sidebar_widget
wp_default_scripts
wp_default_styles
admin_bar_init  
add_admin_bar_menus 
wp_loaded
parse_request
send_headers
parse_query
pre_get_posts
posts_selection 
wp
// ...

About

Geeks Mental is a community that publishes articles and tutorials about Web, Android, Data Science, new techniques and Linux security.