Skip to content

Instantly share code, notes, and snippets.

@jer0dh
Last active July 26, 2021 22:43
Show Gist options
  • Save jer0dh/5bc1bd34cca11575bfe8d5f0faf6b9aa to your computer and use it in GitHub Desktop.
Save jer0dh/5bc1bd34cca11575bfe8d5f0faf6b9aa to your computer and use it in GitHub Desktop.
Wordpress Snippet: Shortcode to loop through custom post type with pagination
<?php
/**
* Edited loop code from: https://wpza.net/how-to-paginate-a-custom-post-type-in-wordpress/
*/
add_shortcode( 'display_whitepapers', 'sz_display_whitepapers_shortcode' );
function sz_display_whitepapers_shortcode( $atts) {
$paged = ( get_query_var( 'paged' ) ) ? get_query_var( 'paged' ) : 1;
$args = array(
'post_type' => 'sz_whitepaper',
'posts_per_page' => 10,
'paged' => $paged
);
ob_start();
$loop = new WP_Query( $args );
if ( $loop->have_posts() ) {
echo '<div class="sz-grid-whitepapers">';
while ( $loop->have_posts() ) : $loop->the_post();
$file = get_field( 'whitepaper_file' );
echo '<div class="sz-grid-item">';
echo '<a href="'. esc_url( $file ) . '" class="sz-grid-image">';
echo get_the_post_thumbnail();
echo '</a>';
echo '<div class="sz-grid-content"><div>';
echo '<h3><a href="' . esc_url( $file ) . '">' . get_the_title() . '</a></h3>';
echo the_content();
echo '</div>';
echo '<div><a class="button" href="' . esc_url( $file ) . '">Download</a></div></div></div>';
endwhile;
?>
<div class="pagination">
<?php
$big = 999999999;
echo paginate_links( array(
'base' => str_replace( $big, '%#%', get_pagenum_link( $big ) ),
'format' => '?paged=%#%',
'current' => max( 1, get_query_var('paged') ),
'total' => $loop->max_num_pages,
'prev_text' => '&laquo;',
'next_text' => '&raquo;'
) );
?>
</div>
<?php
}
wp_reset_postdata();
return ob_get_clean();
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment