这是我遇到问题的代码。 我在返回数组中有所有数据但是当我把它们分页时有问题。
在分页中,如果我每页有10个项目,然后我按下它然后显示第一页的第二行而不是跳过前10个记录
插件链接如下
https://mac-blog.org.ua/wordpress-custom-database-table-example-full/
function prepare_items()
{
global $wpdb;
$table_name = $wpdb->prefix . 'cte'; // do not forget about tables prefix
$per_page = 10; // constant, how much records will be shown per page
$paged = isset($_REQUEST['paged']) ? max(0, intval($_REQUEST['paged']) - 1) : 0;
$current_page = $this->get_pagenum();
$columns = $this->get_columns();
$hidden = array();
$sortable = $this->get_sortable_columns();
// here we configure table headers, defined in our methods
$this->_column_headers = array($columns, $hidden, $sortable);
// [OPTIONAL] process bulk action if any
$this->process_bulk_action();
// will be used in pagination settings
$total_items = $wpdb->get_var("SELECT COUNT(id) FROM $table_name");
// prepare query params, as usual current page, order by and order direction
$orderby = (isset($_REQUEST['orderby']) && in_array($_REQUEST['orderby'], array_keys($this->get_sortable_columns()))) ? $_REQUEST['orderby'] : 'name';
$order = (isset($_REQUEST['order']) && in_array($_REQUEST['order'], array('asc', 'desc'))) ? $_REQUEST['order'] : 'asc';
// [REQUIRED] define $items array
// notice that last argument is ARRAY_A, so we will retrieve array
$this->items = $wpdb->get_results($wpdb->prepare("SELECT * FROM $table_name ORDER BY $orderby $order LIMIT %d OFFSET %d", $per_page, $paged), ARRAY_A);
// [REQUIRED] configure pagination
$this->set_pagination_args(array(
'total_items' => $total_items, // total items defined above
'per_page' => $per_page, // per page constant defined at top of method
'total_pages' => ceil($total_items / $per_page) // calculate pages count
));
}
答案 0 :(得分:1)
如果您的第二页显示第一页的第二行,则您遇到以下问题:
$this->items =
$wpdb->get_results(
$wpdb->prepare(
"SELECT * FROM $table_name ORDER BY $orderby $order LIMIT %d OFFSET %d",
$per_page,
$paged),
ARRAY_A);
特别是,我怀疑当你转到第二页时,$paged == 1
表示你的查询结果偏移1,数据将从第2行开始。
您想要的是,您传递给查询的偏移量是:
offset = ($current_page - 1) * $per_page;
如果代码中的$paged
意味着为$current_page - 1
,请将上述代码更改为以下代码:
$this->items =
$wpdb->get_results(
$wpdb->prepare(
"SELECT * FROM $table_name ORDER BY $orderby $order LIMIT %d OFFSET %d",
$per_page,
$paged * $per_page),
ARRAY_A);