Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- function misha_my_load_more_scripts() {
- $cat= get_the_category();
- $cat_id = $cat[0]->cat_ID;
- //global $wp_query;
- $the_query = new WP_Query(array( 'cat' => $cat_id ));
- // register our main script but do not enqueue it yet
- wp_register_script( 'my_loadmore', get_stylesheet_directory_uri() . '/js/myloadmore.js', array('jquery') );
- // now the most interesting part
- // we have to pass parameters to myloadmore.js script but we can get the parameters values only in PHP
- // you can define variables directly in your HTML but I decided that the most proper way is wp_localize_script()
- wp_localize_script( 'my_loadmore', 'misha_loadmore_params', array(
- 'ajaxurl' => site_url() . '/wp-admin/admin-ajax.php', // WordPress AJAX
- 'posts' => json_encode( $wp_query->query_vars ), // everything about your loop is here
- 'current_page' => $the_query->get_query_var( 'paged' ) ? $the_query->get_query_var('paged') : 1,
- 'max_page' => $the_query->max_num_pages
- ) );
- wp_enqueue_script( 'my_loadmore' );
- }
- add_action( 'wp_enqueue_scripts', 'misha_my_load_more_scripts' );
- function misha_loadmore_ajax_handler(){
- $cat= get_the_category();
- $cat_id = $cat[0]->cat_ID;
- // prepare our arguments for the query
- $args = json_decode( stripslashes( $_POST['query'] ), true );
- $args['cat'] = $cat_id;
- $args['paged'] = $_POST['page'] + 1; // we need next page to be loaded
- $args['post_status'] = 'publish';
- // it is always better to use WP_Query but not here
- query_posts( $args );
- if( have_posts() ) :
- // run the loop
- while( have_posts() ): the_post();
- get_template_part( 'partials/latest-news-article', get_post_format() );
- endwhile;
- endif;
- die;
- }
- add_action('wp_ajax_loadmore', 'misha_loadmore_ajax_handler'); // wp_ajax_{action}
- add_action('wp_ajax_nopriv_loadmore', 'misha_loadmore_ajax_handler'); // wp_ajax_nopriv_{action}
Advertisement
Add Comment
Please, Sign In to add comment