Skip to content

Instantly share code, notes, and snippets.

@jongacnik
Forked from alokstha1/functions.php
Created December 22, 2018 02:08
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save jongacnik/b685d5f1e3f96bee74cade7b1adb1d67 to your computer and use it in GitHub Desktop.
Save jongacnik/b685d5f1e3f96bee74cade7b1adb1d67 to your computer and use it in GitHub Desktop.
WordPress custom pagination with $wpdb->get_results
<?php
$items_per_page = 2;
$page = isset( $_GET['cpage'] ) ? abs( (int) $_GET['cpage'] ) : 1;
$offset = ( $page * $items_per_page ) - $items_per_page;
$query = 'SELECT * FROM '.$table_name;
$total_query = "SELECT COUNT(1) FROM (${query}) AS combined_table";
$total = $wpdb->get_var( $total_query );
$results = $wpdb->get_results( $query.' ORDER BY id DESC LIMIT '. $offset.', '. $items_per_page, OBJECT );
/*
*
* Here goes the loop
*
***/
echo paginate_links( array(
'base' => add_query_arg( 'cpage', '%#%' ),
'format' => '',
'prev_text' => __('&laquo;'),
'next_text' => __('&raquo;'),
'total' => ceil($total / $items_per_page),
'current' => $page
));
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment