Last active
November 23, 2017 23:33
-
-
Save v-skochko/59b1db360304b78c714004e7462e6f5a to your computer and use it in GitHub Desktop.
Ajax load more
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
<?php if ( $wp_query->max_num_pages > 1 ) : ?> | |
<script> | |
var ajaxurl = '<?php echo site_url() ?>/wp-admin/admin-ajax.php'; | |
var true_posts = '<?php echo serialize($wp_query->query_vars); ?>'; | |
var current_page = <?php echo (get_query_var('paged')) ? get_query_var('paged') : 1; ?>; | |
var max_pages = '<?php echo $wp_query->max_num_pages; ?>'; | |
</script> | |
<div id="true_loadmore" class="btn">Load more</div> | |
<?php endif; ?> | |
jQuery(function($){ | |
$('#true_loadmore').click(function(){ | |
$(this).text('Loading...'); | |
var data = { | |
'action': 'loadmore', | |
'query': true_posts, | |
'page' : current_page | |
}; | |
$.ajax({ | |
url:ajaxurl, | |
data:data, | |
type:'POST', | |
success:function(data){ | |
if( data ) { | |
$('#true_loadmore').text('Load more').before(data); | |
current_page++; | |
if (current_page == max_pages) $("#true_loadmore").remove(); | |
} else { | |
$('#true_loadmore').remove(); | |
} | |
} | |
}); | |
}); | |
}); | |
<?php | |
function true_load_posts(){ | |
$args = unserialize(stripslashes($_POST['query'])); | |
$args['paged'] = $_POST['page'] + 1; | |
$args['post_status'] = 'publish'; | |
$q = new WP_Query($args); | |
if( $q->have_posts() ): | |
while($q->have_posts()): $q->the_post(); ?> | |
<div id="post-<?php echo $q->post->ID ?>" class="post-<?php echo $q->post->ID ?> hentry"> | |
</div> | |
<?php | |
endwhile; | |
endif; | |
wp_reset_postdata(); | |
die(); | |
} | |
add_action('wp_ajax_loadmore', 'true_load_posts'); | |
add_action('wp_ajax_nopriv_loadmore', 'true_load_posts'); | |
https://truewp.ru/blog/wordpress/ajax-pagination.html |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment