I have several custom tables that I use for various information that is not related to Wordpress per se. Such as, I have a custom table that I use for certain images.
The custom table is below:
id(int11)
img_link(text)
img_desc(text)
img_wk(text)
img_wishtype(text)
img_dateadded(datetime)
This table will eventually have hundreds of rows, I would like to implement pagination. I am unsure of if it is possible to:
- How can I use WP_Query to do this and include pagination
- If can't use WP_Query, how can I paginate the results to show only say 20 per page?
Below is my code that I tried and failed with. I've viewed several other questions that are similar, but most of them used a posttype. Which would be fine, I just don't know how to declare posttypes or how they would coincide with my custom table.
global $wpdb;
$per_page = 5;
$page = isset( $_GET['cpage'] ) ? abs( (int) $_GET['cpage'] ) : 1;
if ($page > 1) {
$offset = $page * $per_page - $per_page;
} else {
$offset = $page;
}
$the_post = "SELECT img_link,img_wk FROM custom_table ORDER BY id DESC LIMIT $per_page offset $offset";
$details = $wpdb->get_results($the_post, ARRAY_A);
//do foreach to display your post details.
print_r($details);
echo '<br>';
$output = '';
foreach($details as $livewish){
$output .= $livewish['img_link'].'======'.$livewish['img_wk'].'<br>';
}
$total = $wpdb->get_var("SELECT img_link FROM custom_table ORDER BY id DESC");
$output .= paginate_links(array(
'base' => add_query_arg('cpage', '%#%'),
'format' => '',
'prev_text' => __('«'),
'next_text' => __('»'),
'total' => ceil($total / $per_page),
'current' => $page
));
The above code doesn't really work. For some reason it only outputs one row, when I have two rows for testing on. I did notice that if I change ARRAY_A
to OBJECT
the pagination part works, but the SQL breaks. When I change it back to ARRAY_A
I only get one row of results, when there should be two.