Lookhappy Design

03 November 2016

Pagination with a custom wp_query

So I was using a fairly normal WP_query, along the lines of

<?php $query = new WP_Query (array(''posts_per_page=>'6','post_status'=>'published','orderby'=>'menu_order','order'=>'ASC','paged'=>'paged')); ?>

But for some reason pagination was not working, at all. I was trying to use

<?php the_posts_pagination( array(
'mid_size' => 3,
'prev_text' => __( '<', 'welsh-womens-aid' ),
'next_text' => __( '>', 'welsh-womens-aid' ),
) ); ?>

and it was displaying nothing. After a bit of digging around I found out that I needed to tweak my WP_Query slightly and subsequently adjust my pagination call. So now my code looks like this:

<?php $paged = (get_query_var('paged')) ? get_query_var('paged') : 1;
$args = array(
'posts_per_page' => 6,
'post_status'=>'publish',
'orderby' => 'menu_order',
'order'=> 'ASC',
'paged'=>$paged
);
$query = new WP_Query($args); ?>
<?php if ( $query->have_posts() ) : while ( $query->have_posts() ) : $query->the_post(); ?>
<li>
<article class="latest-news">

<div class="thumbnail_holder tablet">
<?php if(has_post_thumbnail()) { ?>
<?php the_post_thumbnail('medium'); ?>
<?php } else { ?>
<img src="<?php bloginfo('template_directory'); ?>/assets/img/News-BG.png" alt="">
<?php } ?>
</div>

<span class="news-date"><?php the_time('d F')?></span>
<h2><a href="<?php the_permalink() ?>"><?php the_title(); ?></a></h2>
<?php the_excerpt(); ?>
<a href="<?php the_permalink() ?>" class="secondary-cta">Read more <span class="fa fa-chevron-right"></span></a>
</article>
</li>

<?php endwhile; ?>
</ul>

<div id="news-navigation">
<?php
$GLOBALS['wp_query']->max_num_pages = $query->max_num_pages;
the_posts_pagination( array(
'mid_size' => 3,
'prev_text' => __( '<', 'welsh-womens-aid' ),
'next_text' => __( '>', 'welsh-womens-aid' ),
) ); ?>

<div class="clearfix"></div>
</div>

<?php else : ?>
<h2><?php _e('Not Found','welsh-womens-aid'); ?></h2>
<p><?php _e("Sorry, but you are looking for something that isn't here.",'welsh-womens-aid'); ?></p>
<?php endif; ?>