|
Tạo phân trang với $wpdb
Nếu website wordpress của bạn tạo thêm bảng và muốn phân trang cho dữ liệu được liệt kê trong bảng thì làm thế nào?
Bạn chỉ băn khoăn tìm công thức tính tổng số trang bạn muốn hiện thị phù hợp với kết quả trích xuất từ bảng đó.
Thật đơn giản sử dụng công thức sau:
//$total: tổng số bài viết (dòng) được tìm thấy
//$posts_per_page: số bài viết (dòng) /1 page
ceil($total / $posts_per_page);
|
Tham khảo ví dụ sau đây:
$data=$wpdb->get_results("select * from wp_mytable");
$page = isset( $_GET['cpage'] ) ? abs( (int) $_GET['cpage'] ) : 1;
$posts_per_page=3; //posts per page
$total=count($data); //total 100 rows
echo paginate_links( array(
'base' => add_query_arg( 'cpage', '%#%' ),
'format' => '',
'current' => $page,
'total' =>ceil($total / $posts_per_page),
'prev_text'=>__('<<'),
'next_text'=>__('>>')
) );
|
Nhận thấy nếu lấy toàn bộ dữ liệu trong bảng là không cần thiết, vừa lãng phí và làm chậm tốc độ sử lý. Chúng ta sẽ sử dụng biến SQL_CALC_FOUND_ROWS để lấy tổng số records được tìm thấy, kết hợp với lệnh LIMIT giới hạn kết quả records thỏa mãn chuỗi lệnh SELECT.
Tạo hàm lấy dữ liệu căn cứ vào trang hiện tại và số lượng cần lấy.
function pagination_wpdb( ){
global $wpdb, $paged, $max_num_pages, $current_date;
$paged = (get_query_var('paged')) ? get_query_var('paged') : 1;
$post_per_page = intval(get_query_var('posts_per_page'));
$offset = ($paged - 1)*$post_per_page;
/* Custom sql here. I left out the important bits and deleted the body
as it will be specific when you have your own. */
$sql = "
SELECT SQL_CALC_FOUND_ROWS {$wpdb->posts}.*
FROM {$wpdb->posts}
....
GROUP BY {$wpdb->posts}.ID
ORDER BY {$wpdb->posts}.post_date DESC
LIMIT ".$offset.", ".$post_per_page."; ";
$sql_result = $wpdb->get_results( $sql, OBJECT);
/* Determine the total of results found to calculate the max_num_pages
for next_posts_link navigation */
$sql_posts_total = $wpdb->get_var( "SELECT FOUND_ROWS();" );
$max_num_pages = ceil($sql_posts_total / $post_per_page);
return $sql_result;
}
|
Hiển thị kết quả và phân trang với previous_posts_link & next_posts_link:
<?php
$pagination_sql = pagination_wpdb();
/*followed by a standart loop to display your results */
foreach($pagination_sql as $item){
echo $item->post_title.'<br/>';
}
?>
<div class="navigation">
<div class="previous panel"><?php previous_posts_link('« previous',$max_num_pages) ?></div>
<div class="next panel"><?php next_posts_link('next »',$max_num_pages) ?></div>
</div>
|
Hình minh họa:

Bạn có thể liệt kê chỉ số trang bởi hàm 'paginate_links'.
<?php
$big = 999999999;
echo paginate_links( array(
'base' => str_replace( $big, '%#%', esc_url( get_pagenum_link( $big ) ) ),
'format' => '?paged=%#%',
'current' => min($paged,1),
'total' =>$max_num_pages,
'prev_text'=>'<<',
'next_text'=>'>>',
) );
?>
|
Kết quả:

Made with help of Dr.Explain
Unregistered version