Ajax Pagination 1,2,3 – Phân trang bằng ajax cho wordpress sử dụng shortcode

banner home FINAL 1050x121 1
huong dan su dung wordpress 2

Trong bài này mình sẽ giới thiệu tới mọi người 1 cách để phân trang bằng ajax khi lấy dữ liệu như bài post hoặc page.

Sau khi hoàn thiện bài hướng dẫn này chúng ta có được shortcode dạng [ajax_pagination] Trong shortcode này chúng ta có các thông số như sau.

[php][ajax_pagination post_type="post" posts_per_page="5" paged="1"][/php]

post_type: slug của post, page hoặc custom post type.
posts_per_page: Số lượng bài hiển thị trên một trang
paged: bắt đầu từ page số mấy. cái này không cần cũng được

Phân trang bằng ajax
Phân trang bằng ajax

Để gọn gàng, dễ hiểu và sau này có thể mở rộng thành plugin thì mình sẽ cho tất cả code của bài vào folder AjaxPagination và bên trong đó sẽ có các file ajax_pagination_wp.phpajax_pagination.js và Ajax_pagination.css

Folder AjaxPagination  sẽ để ở ngay thư mục theme của bạn (wp-contents/themes/[your-theme]/AjaxPagination) và nhớ include vào file functions.php của theme chúng ta đang làm việc.

[php]/*
* Thêm dòng này vào file functions.php của theme
*/
include ‘AjaxPagination/ajax_pagination_wp.php'[/php]

 

Và bây giờ chúng ta sẽ đi vào chi tiết từng file như sau:

Shortcode hiển thị dữ liệu – Phân trang bằng ajax

Tạo file ajax_pagination_wp.php trong folder AjaxPagination nói bên trên. Sau đó gán đoạn code bên dưới này vào

[php]/*******************
* Load Post via ajax with Pagination – Query post
* Author: Zidan
********************/

/******************
* Thêm shortcode ajax_pagination
********************/
function ajax_pagination_svl( $atts ){
$atts = shortcode_atts(
array(
‘posts_per_page’ => 5,
‘paged’ => 1,
‘post_type’ => ‘post’
), $atts,’ajax_pagination’
);
$posts_per_page = intval($atts[‘posts_per_page’]);
$paged = intval($atts[‘paged’]);
$post_type = sanitize_text_field($atts[‘post_type’]);
$allpost = ‘<div id="result_ajaxp">’;
$allpost .= query_ajax_pagination( $post_type, $posts_per_page , $paged );
$allpost .= ‘</div>’;

return $allpost;
}
add_shortcode(‘ajax_pagination’, ‘ajax_pagination_svl’);

function query_ajax_pagination( $post_type = ‘post’, $posts_per_page = 5, $paged = 1){
$args_svl = array(
‘post_type’ => $post_type,
‘posts_per_page’ => $posts_per_page,
‘image_width’ => $image_width,
‘paged’ => $paged,
‘cat’ => 41,
‘post_status’ => ‘publish’
);
$q_svl = new WP_Query( $args_svl );

/*Tổng bài viết trong query trên*/
$total_records = $q_svl->found_posts;

/*Tổng số page*/
$total_pages = ceil($total_records/$posts_per_page);

if($q_svl->have_posts()):
$allpost = ‘<div class="ajax_pagination row large-columns-3" posts_per_page="’.$posts_per_page.’" post_type="’.$post_type.’">’;
while($q_svl->have_posts()):$q_svl->the_post();
$allpost .= ‘<div class="col ajaxp_list_post">’;
$allpost .= ‘<div class="post-image"><a href="’.get_permalink().’" title="’.get_the_title().’">’.get_the_post_thumbnail().'</a></div>’;
$allpost .= ‘<div class="post-info"><a href="’.get_permalink().’" title="’.get_the_title().’"><h3>’.get_the_title().'</h3></a>’;
$allpost .= ‘<p>’. get_the_excerpt() .'</p>’;
// $allpost .= ‘<a href="#" class="btn-regit">Ứng tuyển</a>’;
$allpost .= ‘</div></div>’;
endwhile;
$allpost .= ‘</div>’;
$allpost .= paginate_function( $posts_per_page, $paged, $total_records, $total_pages);
$allpost .='<div class="loading_ajaxp"><div id="circularG"><div id="circularG_1" class="circularG"></div><div id="circularG_2" class="circularG"></div><div id="circularG_3" class="circularG"></div><div id="circularG_4" class="circularG"></div><div id="circularG_5" class="circularG"></div><div id="circularG_6" class="circularG"></div><div id="circularG_7" class="circularG"></div><div id="circularG_8" class="circularG"></div></div></div>’;
endif;wp_reset_query();

return $allpost;
}[/php]

Code phân trang PHP. Dạng 1,2,3… – Phân trang bằng ajax

Đoạn code này giúp chúng ta có phân trang dạng 1,2,3….Hãy copy và dán đoạn code này vào tiếp file ajax_pagination_wp.php bên trên nhé.

[php]/******************
Function phân trang PHP có dạng 1,2,3 …
********************/
function paginate_function($item_per_page, $current_page, $total_records, $total_pages)
{
$pagination = ”;
if($total_pages > 0 && $total_pages != 1 && $current_page <= $total_pages){ //verify total pages and current page number
$pagination .= ‘<ul class="pagination">’;

$right_links = $current_page + 3;
$previous = $current_page – 3; //previous link
$next = $current_page + 1; //next link
$first_link = true; //boolean var to decide our first link

if($current_page > 1){
$previous_link = ($previous<=0)? 1 : $previous;
$pagination .= ‘<li class="first"><a href="#" data-page="1" title="First">&laquo;</a></li>’; //first link
$pagination .= ‘<li><a href="#" data-page="’.$previous_link.’" title="Previous">&lt;</a></li>’; //previous link
for($i = ($current_page-2); $i < $current_page; $i++){ //Create left-hand side links
if($i > 0){
$pagination .= ‘<li><a href="#" data-page="’.$i.’" title="Page’.$i.’">’.$i.'</a></li>’;
}
}
$first_link = false; //set first link to false
}

if($first_link){ //if current active page is first link
$pagination .= ‘<li class="first active">’.$current_page.'</li>’;
}elseif($current_page == $total_pages){ //if it’s the last active link
$pagination .= ‘<li class="last active">’.$current_page.'</li>’;
}else{ //regular current link
$pagination .= ‘<li class="active">’.$current_page.'</li>’;
}

for($i = $current_page+1; $i < $right_links ; $i++){ //create right-hand side links
if($i<=$total_pages){
$pagination .= ‘<li><a href="#" data-page="’.$i.’" title="Page ‘.$i.’">’.$i.'</a></li>’;
}
}
if($current_page < $total_pages){
$next_link = ($i > $total_pages)? $total_pages : $i;
$pagination .= ‘<li><a href="#" data-page="’.$next_link.’" title="Next">&gt;</a></li>’; //next link
$pagination .= ‘<li class="last"><a href="#" data-page="’.$total_pages.’" title="Last">&raquo;</a></li>’; //last link
}

$pagination .= ‘</ul>’;
}
return $pagination; //return pagination links
}[/php]

Gọi và xử lý ajax trong WordPress – Phân trang bằng ajax

Hàm này giúp các bạn load dữ liệu bằng ajax. Để biết thêm về ajax trong worpress bạn tham khảo thêm bài này: Sử dụng ajax trong wordpress

[php]/** Xử lý Ajax trong WordPress */
add_action( ‘wp_ajax_LoadPostPagination’, ‘LoadPostPagination_init’ );
add_action( ‘wp_ajax_nopriv_LoadPostPagination’, ‘LoadPostPagination_init’ );
function LoadPostPagination_init() {
$posts_per_page = intval($_POST[‘posts_per_page’]);
$paged = intval($_POST[‘data_page’]);
$post_type = sanitize_text_field($_POST[‘post_type’]);
$allpost = query_ajax_pagination( $post_type, $posts_per_page , $paged );
echo $allpost;
exit;
}[/php]

Thêm jQuery và Css vào Web thông qua function

Đoạn code này để gọi file js và css vào theme.

[php]add_action( ‘wp_enqueue_scripts’, ‘devvn_useAjaxPagination’, 1 );
function devvn_useAjaxPagination() {
/** Thêm js vào website */
wp_enqueue_script( ‘devvn-ajax’, esc_url( trailingslashit( get_stylesheet_directory_uri() ) . ‘AjaxPagination/ajax_pagination.js’ ), array( ‘jquery’ ), ‘1.0’, true );
$php_array = array(
‘admin_ajax’ => admin_url( ‘admin-ajax.php’ )
);
wp_localize_script( ‘devvn-ajax’, ‘svl_array_ajaxp’, $php_array );

/*Thêm css vào website*/
wp_enqueue_style( ‘ajaxp’, esc_url( trailingslashit( get_stylesheet_directory_uri() )) . ‘AjaxPagination/Ajax_pagination.css’, false);
}[/php]

Js và css trong hướng dẫn này – Phân trang bằng ajax

Dưới đây là đoạn js để gửi thông số và nhận kết quả mà ajax gửi ra để hiển thị.

[php]// JavaScript Document
(function($) {
$(document).ready(function(){
$( ‘#result_ajaxp’ ).on( ‘click’,’ ul.pagination a’, function( e ) {
/** Prevent Default Behaviour */
e.preventDefault();
/** Get data-page */
var data_page = $(this).attr( ‘data-page’ );
var posts_per_page = $(‘.ajax_pagination’).attr( ‘posts_per_page’ );
var post_type = $(‘.ajax_pagination’).attr( ‘post_type’ );
/** Ajax Call */
$.ajax({
cache: false,
timeout: 8000,
url: svl_array_ajaxp.admin_ajax,
type: "POST",
data: ({
action : ‘LoadPostPagination’,
data_page : data_page,
posts_per_page : posts_per_page,
post_type : post_type
}),
beforeSend: function() {
$( ‘.loading_ajaxp’ ).css( ‘display’,’block’ );
},
success: function( data, textStatus, jqXHR ){
$( ‘#result_ajaxp’ ).html( data );
},
error: function( jqXHR, textStatus, errorThrown ){
console.log( ‘The following error occured: ‘ + textStatus, errorThrown );
},
complete: function( jqXHR, textStatus ){
}
});
});
});
})(jQuery);[/php]

Còn css các bạn tham khảo thêm

Src: levantoan
Chúc các bạn thành công! Bạn có thể xem qua các bài viết khác về thủ thuật WordPress

0/5 (0 Reviews)

Theo dõi và cập nhật tin tức AZ9s thông qua các kênh truyền thông:

- Zalo Channel

- Facebook Channel

- Youtube Channel

banner home FINAL 1050x121 1
5 1 vote
Article Rating
Nhận thông báo qua Email
Nhận thông báo cho
guest

0 Comments
Inline Feedbacks
View all comments
0
Hãy để lại bình luận của bạn!x
()
x