Archive pagination as a shortcode

There might be times when you would want the default GeneratePress archive pagination to conditionally appear in certain archives (eg: you might don’t want it to appear on the blog page). You could hide it with CSS but there is also another method that could prove more useful.

You could create a shortcode and use a hook element to conditionally display it wherever you want.

The below code snippet would remove the author pagination from the site:

	remove_action( 'generate_after_loop', 'generate_do_post_navigation' );	

Then, you would build a shortcode that would output the pagination:

add_shortcode( 'gm_pagination', function() {

        echo '<div class="your-pagination-class">';
        the_posts_pagination( array(
	    'end_size' => 2,
	    'mid_size' => apply_filters( 'generate_pagination_mid_size', 1 ),
            'prev_text' => apply_filters( 'generate_previous_link_text', __( '&larr; Previous', 'generatepress' ) ),
	    'next_text' => apply_filters( 'generate_next_link_text', __( 'Next &rarr;', 'generatepress' ) ),
	) );
        echo '</div>';

    return ob_get_clean();

Finally, create a hook element, make sure Shortcodes are displayed and enter [gm_archive_pagination] in the text field. The generate_after_loop hook is a good location for the pagination to be displayed but the beauty of it is that you could inject the pagination in all the available GeneratePress hooks!

Archive pagination shortcode