0

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..

0

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
// ...
  • Thanks Milo - but the template_redirect doesn't work either? – Mac Luc Feb 10 '15 at 21:30
  • scripts should be enqueued on wp_enqueue_scripts action. var_dump( $wp_query ) and see what it contains. – Milo Feb 10 '15 at 21:34
  • isn't that whats happening? – Mac Luc Feb 10 '15 at 21:37
  • wp_enqueue_scripts is the action within which you should use the wp_enqueue_script function. – Milo Feb 10 '15 at 21:58
  • ahh - but how do I achieve that? :-) – Mac Luc Feb 10 '15 at 22:05

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.