Last active
September 22, 2018 03:38
-
-
Save bryanrsebastian/c8c3e9d141c76ffcb2fd780ed87820a2 to your computer and use it in GitHub Desktop.
This snippets is compatible even there is a year and month in the url.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/** | |
* Add first and last button to the | |
* default pagination of wordpress | |
* | |
* Note: Don't forget to initialize your default | |
* query to limit your post in pre_get_post hook | |
* | |
* @var string $post_type name of your post type | |
* @var int $total_post number of total post to get the number of pagination | |
* @return void pagination | |
*/ | |
function first_last_pagination( $post_type, $total_post ) { | |
global $wp_query; | |
$archive_link = get_post_type_archive_link( $post_type ); | |
$current_link = ( isset( $_SERVER['HTTPS'] ) ? "https" : "http" ) . "://$_SERVER[HTTP_HOST]$_SERVER[REQUEST_URI]"; | |
/* Generate First Link */ | |
if( isset( $wp_query->query['year'] ) ) { | |
/* Insert the year */ | |
$first_link = $archive_link . $wp_query->query['year'] . '/'; | |
/* Insert the month */ | |
if( isset( $wp_query->query['monthnum'] ) ) | |
$first_link .= $wp_query->query['monthnum'] . '/'; | |
} | |
else { | |
$first_link = $archive_link; | |
} | |
/* Generate Last Link */ | |
if( isset( $wp_query->query['year'] ) ) { | |
/* Insert the year with the current page number */ | |
$last_link = $archive_link . $wp_query->query['year'] . '/page/' . ceil( $wp_query->found_posts / $total_post ) . '/'; | |
/* Insert the month with the current page number */ | |
if( isset( $wp_query->query['monthnum'] ) ) | |
$last_link = $archive_link . $wp_query->query['year'] . '/' . $wp_query->query['monthnum'] . '/page/' . ceil( $wp_query->found_posts / $total_post ) . '/'; | |
} | |
else { | |
$last_link = $archive_link . 'page/' . ceil( $wp_query->found_posts / $total_post ) . '/'; | |
} | |
/* Check if the current link is the first page to hide the button */ | |
if( $current_link != $first_link ) | |
echo '<a href="'. $first_link .'" class="first">First</a>'; | |
echo paginate_links( array( | |
'base' => str_replace( 999999999, '%#%', esc_url( get_pagenum_link( 999999999 ) ) ), | |
'format' => '?paged=%#%', | |
'current' => ( get_query_var('paged') ) ? get_query_var('paged') : 1, | |
'prev_text' => 'Previous', | |
'next_text' => 'Next', | |
) ); | |
/* Check if the current link is the last page to hide the button */ | |
if( $current_link != $last_link && ceil( $wp_query->found_posts / $total_post ) > 1 ) | |
echo '<a href="'. $last_link .'" class="last">Last</a>'; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment