Guest User

Untitled

a guest
May 2nd, 2019
186
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.88 KB | None | 0 0
  1. function misha_my_load_more_scripts() {
  2. $cat= get_the_category();
  3. $cat_id = $cat[0]->cat_ID;
  4.  
  5. //global $wp_query;
  6. $the_query = new WP_Query(array( 'cat' => $cat_id ));
  7.  
  8. // register our main script but do not enqueue it yet
  9. wp_register_script( 'my_loadmore', get_stylesheet_directory_uri() . '/js/myloadmore.js', array('jquery') );
  10.  
  11. // now the most interesting part
  12. // we have to pass parameters to myloadmore.js script but we can get the parameters values only in PHP
  13. // you can define variables directly in your HTML but I decided that the most proper way is wp_localize_script()
  14. wp_localize_script( 'my_loadmore', 'misha_loadmore_params', array(
  15. 'ajaxurl' => site_url() . '/wp-admin/admin-ajax.php', // WordPress AJAX
  16. 'posts' => json_encode( $wp_query->query_vars ), // everything about your loop is here
  17. 'current_page' => $the_query->get_query_var( 'paged' ) ? $the_query->get_query_var('paged') : 1,
  18. 'max_page' => $the_query->max_num_pages
  19. ) );
  20.  
  21. wp_enqueue_script( 'my_loadmore' );
  22. }
  23.  
  24. add_action( 'wp_enqueue_scripts', 'misha_my_load_more_scripts' );
  25.  
  26. function misha_loadmore_ajax_handler(){
  27. $cat= get_the_category();
  28. $cat_id = $cat[0]->cat_ID;
  29.  
  30. // prepare our arguments for the query
  31. $args = json_decode( stripslashes( $_POST['query'] ), true );
  32. $args['cat'] = $cat_id;
  33. $args['paged'] = $_POST['page'] + 1; // we need next page to be loaded
  34. $args['post_status'] = 'publish';
  35.  
  36. // it is always better to use WP_Query but not here
  37. query_posts( $args );
  38.  
  39. if( have_posts() ) :
  40.  
  41. // run the loop
  42. while( have_posts() ): the_post();
  43. get_template_part( 'partials/latest-news-article', get_post_format() );
  44.  
  45. endwhile;
  46.  
  47. endif;
  48. die;
  49. }
  50.  
  51.  
  52.  
  53.  
  54. add_action('wp_ajax_loadmore', 'misha_loadmore_ajax_handler'); // wp_ajax_{action}
  55. add_action('wp_ajax_nopriv_loadmore', 'misha_loadmore_ajax_handler'); // wp_ajax_nopriv_{action}
Advertisement
Add Comment
Please, Sign In to add comment