Guest User

Untitled

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