Can I use pagination with class $ wpdb?

Let's say I want to use the $ wpdb class to extract image locations from a database, then create a gallery of images. I have this code, but when I click "next", the link does not seem to go anywhere. Did I miss something?

<?php
global $wpdb;
$wpdb->show_errors();
$offset = 0;
if( isset($_GET['page']) && !empty($_GET['page']) ){
$offset =  ($_GET['page']-1) * 10; // (page 2 - 1)*10 = offset of 10
}
$pics = $wpdb->get_col("SELECT pic_thumb_url FROM wp3_bp_album 
WHERE owner_type = 'user' ORDER BY title DESC
LIMIT 10 OFFSET $offset"
);
//LIMIT shows 10 results per page
//OFFSET will 'skip' this number off results. On page 1 the offset is 0 on page 2 it is 10       (if 10 results per page)
foreach($pics as $pic) :
echo '<a href ="'. '#' .'" > <img src="' . $pic . '">' . '</a>';

endforeach; 


/*
pagination
*/
?>
<a href="/community/?page=<?php echo $_GET['page']-1 ?>">previous</a>
<a href="/community/?page=<?php echo $_GET['page']+1 ?>">next</a>

Can I implement pagination with this?

+3
source share
1 answer

You can not use the built-in pagination, but to use the pagination use OFFSETand LIMITin its request. So do your own pagination:

<?php
$offset = 0;
if(isset($_GET['page']) && !empty($_GET['page']) {
    $offset =  ($_GET['page']-1) * 10; // (page 2 - 1)*10 = offset of 10
}
$wpdb->get_col("SELECT pic_thumb_url FROM wp3_bp_album 
    WHERE owner_type = 'user' ORDER BY title DESC
    LIMIT 10 OFFSET $offset"
);
//LIMIT shows 10 results per page
//OFFSET will 'skip' this number off results. On page 1 the offset is 0 on page 2 it is 10 (if 10 results per page)

/*
pagination
*/
?>
<a href="/currentpage/?page=<?php echo $_GET['page']-1 ?>">previous</a>
<a href="/currentpage/?page=<?php echo $_GET['page']+1 ?>">next</a>

Not perfect, it does not check whether you are on the first or last page, but at least the first check that you must create yourself.

+3
source

All Articles