Вот Билл Эрриксон скомпилированный под вашу задачу.
php
/**
* Javascript for Load More
*
*/
function be_load_more_js() {
if ( !is_singular( 'post' ) )
return;
$query = array(
'post__not_in' => array( get_queried_object_id() ),
'category_name' => ea_first_term( 'category', 'slug' ),
'posts_per_page' => 3
);
$args = array(
'url' => admin_url( 'admin-ajax.php' ),
'query' => $query,
);
wp_enqueue_script( 'be-load-more', get_stylesheet_directory_uri() . '/js/load-more.js', array( 'jquery' ), '1.0', true );
wp_localize_script( 'be-load-more', 'beloadmore', $args );
}
add_action( 'wp_enqueue_scripts', 'be_load_more_js' );
/**
* AJAX Load More
*
*/
function be_ajax_load_more() {
$args = isset( $_POST[ 'query' ] ) ? array_map( 'esc_attr', $_POST[ 'query' ] ) : array();
$args[ 'post_type' ] = isset( $args[ 'post_type' ] ) ? esc_attr( $args[ 'post_type' ] ) : 'post';
$args[ 'paged' ] = esc_attr( $_POST[ 'page' ] );
$args[ 'post_status' ] = 'publish';
ob_start();
$loop = new WP_Query( $args );
if ( $loop->have_posts() ): while ( $loop->have_posts() ): $loop->the_post();
be_post_summary();
endwhile; endif;
wp_reset_postdata();
$data = ob_get_clean();
wp_send_json_success( $data );
wp_die();
}
add_action( 'wp_ajax_be_ajax_load_more', 'be_ajax_load_more' );
add_action( 'wp_ajax_nopriv_be_ajax_load_more', 'be_ajax_load_more' );
/**
* First Term
* Helper Function
*/
function ea_first_term($taxonomy, $field) {
$terms = get_the_terms( get_the_ID(), $taxonomy );
if ( empty( $terms ) || is_wp_error( $terms ) )
return false;
// If there's only one term, use that
if ( 1 == count( $terms ) ) {
$term = array_shift( $terms );
} else {
$term = array_shift( $list );
}
// Output
if ( $field && isset( $term->$field ) )
return $term->$field;
else
return $term;
}
js
jQuery(function ($) {
$('.post-listing').append('<span class="load-more">Click here to load earlier stories</span>');
var button = $('.post-listing .load-more');
var page = 2;
var loading = false;
var scroll = false;
var scrollHandling = {
allow: true,
reallow: function () {
scrollHandling.allow = true;
},
delay: 400 //(milliseconds) adjust to the highest acceptable value
};
function morer() {
if (!loading) {
loading = true;
var data = {
action: 'be_ajax_load_more',
page: page,
query: beloadmore.query,
};
$.post(beloadmore.url, data, function (res) {
if (res.success) {
$('.post-listing').append(res.data);
$('.post-listing').append(button);
page = page + 1;
loading = false;
} else {
// console.log(res);
}
}).fail(function (xhr, textStatus, e) {
// console.log(xhr.responseText);
});
}
}
$('body').on('click', '.load-more', function () {
if (scroll === false) {
morer();
$('.load-more').remove();
scroll = true;
}
});
$(window).scroll(function () {
if (scroll === true) {
if (!loading && scrollHandling.allow) {
scrollHandling.allow = false;
setTimeout(scrollHandling.reallow, scrollHandling.delay);
var offset = $(button).offset().top - $(window).scrollTop();
if (2000 > offset) {
morer();
}
}
}
});
});