RPeraltaJr
10/6/2019 - 3:17 AM

Loop through posts (and pagination)

<?php 

    // * WP_Query Args: https://gist.github.com/fazlurr/10830359
    $paged = get_query_var('paged') ? get_query_var('paged') : 1;
    $args = array(
        'post_type'         => 'post',
        'posts_per_page'    => get_option('posts_per_page'), // gets 'posts per page' value from WP Dashboard (Settings > Reading)
        'paged'             => $paged
    );
    
    // * filter by query/keyword
    if(isset($_GET['s']) && !empty($_GET['s'])): 
        $keyword = sanitize_text_field($_GET['s']);
        $args['s'] = $keyword;
    endif;
    
    // * filter by category
    if(isset($_GET['category_name']) && !empty($_GET['category_name'])): 
        $category_name = sanitize_text_field($_GET['category_name']);
        $args['category_name'] = $category_name;
    endif;
                
    $post_query = new WP_Query($args); // * query
    $max_pages = $post_query->max_num_pages; // * get total # of pages
?>

<?php if( $post_query->have_posts() ): ?>
    <?php while( $post_query->have_posts() ): $post_query->the_post(); ?>

    <section class="posts">
        <div class="container">
            <div class="col col--title">
                <div class="box">
                    <h1 class="font-display-1">
                        <strong><?php echo the_title(); ?></strong>
                    </h1>
                    <ul class="list-inline">
                        <li><p><?php echo get_the_date(); ?></p></li>
                        <li><p>|</p></li>
                        <li><p><?php echo ucfirst(get_author_name()); ?></p></li>
                    </ul>
                </div>
            </div>
            <div class="col col--content">
                <div class="box">
                    <div class="body-copy--lg"><?php echo get_the_content(); ?></div>
                    <p class="body-copy--lg">
                        <a href="<?php echo get_the_permalink(); ?>"><strong>Read Full Article</strong></a>
                    </p>
                </div>
            </div>
        </div>
    </section>

    <?php endwhile; ?>
<?php 
  endif; 
  wp_reset_query(); // Destroys the previous query and sets up a new query.  
?>

<div class="posts__pagination">
    <div class="container">
        <div class="posts_pagination__list">
            <?php echo post_pagination(); ?>
        </div>
    </div>
</div>
<?php 

if ( !function_exists( 'post_pagination' ) ):
    function post_pagination() {
        global $post_query;
        $pager = 999999999; // need an unlikely integer

        echo paginate_links( array(
            'base' => str_replace( $pager, '%#%', esc_url( get_pagenum_link( $pager ) ) ),
            'format' => '?paged=%#%',
            'current' => max( 1, get_query_var('paged') ),
            'total' => $post_query->max_num_pages
        ) );
    }
endif;