Chào các bạn, ở bài này mình sẽ hướng dẫn cho các bạn về Infinite Scroll.
Infinite Scroll trong WordPress
Chắc hẳn các bạn cũng đã biết infinite scroll là gì rồi phải không? Nó được dùng để load liên tục các bài post khi bạn scroll đến một mức độ nhất định nào đó mà ta tự thiết lập. Vậy bây giờ chúng ta cùng làm một Infinite Scroll trên WordPress nhé.
Để thực hiện Infinite Scroll trên WordPress chúng ta cần phải làm một việc, chính là tạo Ajax trong WordPress. Ajax ( Asynchronous JavaScript and XML ) là một cách để tương tác với máy chủ và xem kết quả mà không phải tải lại trang của mình. Giờ thì mình cùng nhau bắt đầu làm nhé.
Bước 1: Các bạn cần tạo một shortcode [ajax_posts] trong template site WordPRess của bạn. Shortcode API trong WordPress hoạt động rất đơn giản, đầu tiên bạn cần phải tạo một callback function để thực thi mỗi khi bạn gọi shortcode.
Tạo shortcode trong file functions.php của bạn.
function script_load_more($args = array()) {
//initial posts load
echo '<div id="ajax-primary" class="content-area">';
echo '<div id="ajax-content" class="content-area">';
ajax_script_load_more($args);
echo '</div>';
echo '<div class="btn__load-more-post">';
echo '<button id="loadMore" data-page="1" data-url="'.admin_url("admin-ajax.php").'" >Xem thêm</button>';
echo '</div>';
echo '</div>';
}
/*
* create short code.
*/
add_shortcode('ajax_posts', 'script_load_more');
Bước 2: Tạo CallBack Functions để loadpost trên WordPress
/*
* load more script call back
*/
function ajax_script_load_more($args) {
//init ajax
$ajax = false;
//check ajax call or not
if(!empty($_SERVER['HTTP_X_REQUESTED_WITH']) &&
strtolower($_SERVER['HTTP_X_REQUESTED_WITH']) == 'xmlhttprequest') {
$ajax = true;
}
//number of posts per page default
$num =4;
//page number
$paged = ( get_query_var( 'paged' ) ) ? get_query_var( 'paged' ) : 1 + 1;
//args
$args = array(
'post_type' => 'post',
'post_status' => 'publish',
'posts_per_page' =>$num,
'paged'=>$paged
);
//query
$query = new WP_Query($args);
//check
if ($query->have_posts()):
//loop articales
while ($query->have_posts()): $query->the_post();
//include articles template
include 'ajax-content.php';
endwhile;
else:
echo 0;
endif;
//reset post data
wp_reset_postdata();
//check ajax call
if($ajax) die();
}
Bước 3: Tạo file ajax-content.php (bạn có thể đặt tên khác. miễn sao giống với tên file bạn include trong CallBack Function là được) và bạn có thể tùy chỉnh lại đoạn code bên dưới theo ý mình nhé..
<article id="post-<?php the_ID(); ?>" <?php post_class(); ?>>
<header class="entry-header">
<?php the_title( '<h3 class="entry-title"><a href="' . esc_url( get_permalink() ) . '" rel="bookmark">', '</a></h3>' );?>
</header>
<div class="entry-content">
<?php the_content( 'Continue reading... ' . get_the_title() ); ?>
</div>
</article>
Bước 4: Tạo Ajax action hook để gọi function ‘ajax_script_load_more’.
/*
* load more script ajax hooks
*/
add_action('wp_ajax_nopriv_ajax_script_load_more', 'ajax_script_load_more');
add_action('wp_ajax_ajax_script_load_more', 'ajax_script_load_more');
Tạo file script_ajax.js trong thư mục js của bạn và tùy chỉnh. Ở đây mình có 2 lựa chọn cho các bạn để add code vào file script_ajax.js:
1/ LoadMore với button.
CodjQuery.noConflict($);
/* Ajax functions */
jQuery(document).ready(function($) {
//onclick
$("#loadMore").on('click', function(e) {
//init
var that = $(this);
var page = $(this).data('page');
var newPage = page + 1;
var ajaxurl = that.data('url');
//ajax call
$.ajax({
url: ajaxurl,
type: 'post',
data: {
page: page,
action: 'ajax_script_load_more'
},
error: function(response) {
console.log(response);
},
success: function(response) {
//check
if (response == 0) {
$('#ajax-content').append('<div class="text-center"><h3>You reached the end of the line!</h3><p>No more posts to load.</p></div>');
$('#loadMore').hide();
} else {
that.data('page', newPage);
$('#ajax-content').append(response);
}
}
});
});
});
2/ LoadMore Infinite Scroll
jQuery.noConflict($);
/* Ajax functions */
jQuery(document).ready(function($) {
//find scroll position
$(window).scroll(function() {
//init
var that = $('#loadMore');
var page = $('#loadMore').data('page');
var newPage = page + 1;
var ajaxurl = $('#loadMore').data('url');
//check
if ($(window).scrollTop() == $(document).height() - $(window).height()) {
//ajax call
$.ajax({
url: ajaxurl,
type: 'post',
data: {
page: page,
action: 'ajax_script_load_more'
},
error: function(response) {
console.log(response);
},
success: function(response) {
//check
if (response == 0) {
//check
if ($("#no-more").length == 0) {
$('#ajax-content').append('<div id="no-more" class="text-center"><h3>You reached the end of the line!</h3><p>No more posts to load.</p></div>');
}
$('#loadMore').hide();
} else {
$('#loadMore').data('page', newPage);
$('#ajax-content').append(response);
}
}
});
}
});
});
cuối cùng bạn add ShortCode vào nơi mà bạn muốn nó thực hiện.
<?php echo do_shortcode('[ajax_posts]'); ?>
*Nếu bạn làm như trên mà vẫn chưa chạy thì bạn add thêm đoạn code sau vào dưới nơi bạn tạo Ajax action hook.
add_action( 'wp_enqueue_scripts', 'ajax_enqueue_script' );
/*
* enqueue js script call back
*/
function ajax_enqueue_script() {
wp_enqueue_script( 'script_ajax', get_theme_file_uri( '/js/script_ajax.js' ), array( 'jquery' ), '1.0', true );
}