Skip to content

Instantly share code, notes, and snippets.

@alokstha1
Created September 14, 2017 08:13
Show Gist options
  • Star 19 You must be signed in to star a gist
  • Fork 7 You must be signed in to fork a gist
  • Save alokstha1/2e8f7ed6517917aa345fc6f1f65f1fbd to your computer and use it in GitHub Desktop.
Save alokstha1/2e8f7ed6517917aa345fc6f1f65f1fbd 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
));
@CristianoMZN
Copy link

Thanks man!

@alokstha1
Copy link
Author

Thanks man!

You are welcome!

@BlogSafe
Copy link

BlogSafe commented Jul 9, 2021

4 years later and still works like a charm. Thanks!

@alokstha1
Copy link
Author

4 years later and still works like a charm. Thanks!

@BlogSafe Glad it helped.

@manager-wiseTech
Copy link

Great hack.

@Roner1k
Copy link

Roner1k commented May 24, 2022

Thanks!

@blipps199
Copy link

Thanks!

@sonwebtl
Copy link

thanks good!

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment