Why ?
Pagination is almost everywhere 🙂
Any Assumptions?
Let’s assume that you’re developing custom theme with custom post types and you don’t want to use a pagination plugin.
Where ?
Before the [php] wp_reset_postdata(); [/php] usage examples
How ?
Create a function, and paste it inside your functions.php file
[php]
/**
* Generates the user pagination for custom and default loops
*
* @global object $wp_query
* @param object $query used within a custom loop
*/
function rgicgier_pagination($query = null) {
if ( !$query ) {
global $wp_query;
$query = $wp_query;
}
$big = 999999999; // need an unlikely integer
$pagination = paginate_links( array(
‘base’ => str_replace( $big, ‘%#%’, esc_url( get_pagenum_link( $big ) ) ),
‘format’ => ‘?paged=%#%’,
‘current’ => max( 1, get_query_var( ‘paged’ ) ),
‘total’ => $query->max_num_pages,
‘prev_text’ => ‘« Previous’,
‘next_text’ => ‘Next »’,
‘type’ => ‘list’,
) );
?>
‘skeleton_projects’,
‘paged’ => get_query_var( ‘paged’ ),
);
$slider_query = new WP_Query( $args );
// some code here
// some code here
wp_reset_postdata(); // used ALWAYS after custom query
[/php]
Fork it at: github.com.
Explanation ?
WordPress needs to know what kind of loop we’re currently within, hence if it’s a custom loop, we need to make sure that we pass the instantiated WP_Query object to the function, otherwise it will use the global variable $wp_query, that will fail outside default loop.
[php]
function rgicgier_pagination($query = null) {
if ( !$query ) {
global $wp_query;
$query = $wp_query;
}
rgicgier_pagination( $slider_query );
[/php]
It’s also worth noticing that we’ve added ‘paged’ argument to the argument of the query:
[php]
$args = array(
‘post_type’ => ‘skeleton_projects’,
‘paged’ => get_query_var( ‘paged’ ),
);
[/php]
In a nutshell ?
While $query variable passed to our function will provide us with the HTML code for pagination (otherwise it won’t render).
The ‘paged’ key will make sure that the pagination will work as planned.
P.S.
Shortie inspired by