getButterfly Logo getButterfly

First of all, we need to write a class to handle pagination. Second, we need to display the pagination in our custom WordPress table (in the back-end section, for a plugin or for theme settings).

Here’s the class:

And here’s the sample usage:

include 'classes/Pagination.php';

$items = $wpdb->get_results("SELECT field1, field2, field3 FROM wp_custom_table");
$items = $wpdb->num_rows;

if ($items > 0) {
    $p = new Pagination;

    if (!isset($_GET['paging'])) {
        $p->page = 1;
    } else {
        $p->page = (int) $_GET['paging'];

    $limit = 'LIMIT ' . ($p->page - 1) * $p->limit . ', ' . $p->limit;
} else {
    echo '<p>No records found!</p>';

$results = $wpdb->get_results("SELECT field1, field2, field3 FROM wp_custom_table $limit", ARRAY_A);
<div class="tablenav"><?php echo $p->show(); ?></div>
<table class="wp-list-table widefat striped posts">
            <th scope="col">Field 1</th>
            <th scope="col">Field 2</th>
            <th scope="col">Field 2</th>
    foreach($results as $row) {
        echo '<tr>';
            echo '<td>' . $row['field1'] . '</td>';
            echo '<td>' . $row['field2'] . '</td>';
            echo '<td>' . $row['field3'] . '</td>';
        echo '</tr>';

And that is all. The pagination class is compatible with WordPress 4.7+.

Subscribe to getButterfly Blog

Once a week or so we send an email with our best content. We never bug you, we just send you our latest piece of content.

If you found any value in this post, agree, disagree, or have anything to add - please do. I use comments as my #1 signal for what to write about. Read our comment policy before commenting! Comments such as "Thank you!", "Awesome!", "You're the man!" are either marked as spam or stripped from URL.

Leave a Reply

Your email address will not be published. Required fields are marked *