Created
June 8, 2020 18:40
-
-
Save salehahmadbabu/94c0583808082e2a894c5a1d82e25877 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
global $wp_query; | |
wp_register_script( 'understrap_loadmore', get_stylesheet_directory_uri() . '/myloadmore.js', array('jquery') ); | |
wp_localize_script( | |
'understrap_loadmore', | |
'understrap_loadmore_params', | |
array( | |
'ajaxurl' => site_url() . '/wp-admin/admin-ajax.php', | |
'posts' => json_encode( $wp_query->query_vars ), | |
'current_page' => get_query_var( 'paged' ) ? get_query_var('paged') : 1, | |
'max_page' => $wp_query->max_num_pages | |
) ); | |
wp_enqueue_script( 'understrap_loadmore' ); | |
// my-loadmore.js | |
jQuery(function($){ | |
var canBeLoaded = true, | |
bottomOffset = 2000; | |
$(window).scroll(function(){ | |
var data = { | |
'action': 'loadmore', | |
'query': understrap_loadmore_params.posts, | |
'page' : understrap_loadmore_params.current_page | |
}; | |
if( $(document).scrollTop() > ( $(document).height() - bottomOffset ) && canBeLoaded == true ){ | |
$.ajax({ | |
url : understrap_loadmore_params.ajaxurl, | |
data:data, | |
type:'POST', | |
beforeSend: function( xhr ){ | |
canBeLoaded = false; | |
}, | |
success:function(data){ | |
if( data ) { | |
$('#main').find('article:last-of-type').after( data ); | |
canBeLoaded = true; | |
understrap_loadmore_params.current_page++; | |
} | |
} | |
}); | |
} | |
}); | |
}); | |
// nonce functions | |
function understrap_loadmore_ajax_handler(){ | |
$args = json_decode( stripslashes( $_POST['query'] ), true ); | |
$args['paged'] = $_POST['page'] + 1; | |
$args['post_status'] = 'publish'; | |
query_posts( $args ); | |
if( have_posts() ) : | |
while( have_posts() ): the_post(); | |
get_template_part( 'template-parts/post/content', get_post_format() ); | |
endwhile; | |
endif; | |
die; | |
} | |
add_action('wp_ajax_loadmore', 'understrap_loadmore_ajax_handler'); | |
add_action('wp_ajax_nopriv_loadmore', 'understrap_loadmore_ajax_handler'); | |
blog url: https://rudrastyh.com/wordpress/load-more-posts-ajax.html |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment