Issue
I'm working on a WordPress site and I've created a page template that displays posts by a category slug. To do this, I create a field for the page, WP_Catid, and set it equal to the category slug I want to display posts from. However, I only want five posts to show up per page with pagination links at the bottom of those posts. How do I get the pagination links to display properly?
My code is as follows:
<div id="container">
<div id="content" role="main">
<?php
$btpgid=get_queried_object_id();
$btmetanm=get_post_meta( $btpgid, 'WP_Catid','true' );
$paged = (get_query_var('paged')) ? get_query_var('paged') : 1;
$args = array( 'posts_per_page' => 5,
'category_name' => $btmetanm,
'paged' => $paged,
'post_type' => 'post' );
$myposts = get_posts( $args );
foreach ( $myposts as $post ) : setup_postdata( $post );
echo "<div style='border:2px groove black; margin-bottom:5px;'><h3 class='btposth'>";
the_title();
echo "</h3><div class='btpostdiv'>";
the_content();
echo "</div></div>";
endforeach;
next_posts_link( 'Older Entries'); //not displaying
previous_posts_link('Newer Entries »'); //not displaying
wp_reset_postdata();
?>
</div><!-- #content -->
</div><!-- #container -->
Solution
The sweet and short of this, don't use get_posts
if you need paginated queries. get_posts
works perfectly if you are going to use a custom query that doesn't need pagination, but it really becomes a big complicated mess when you need to introduce pagination.
I think the easiest and most appropriate here is to make use of WP_Query
to construct your custom query, that is, if you can't use pre_get_posts
to alter the main query to get your desired output from the main query.
I do think that next_posts_link()
and previous_posts_link()
is better to use with a custom query, ie with WP_Query
. You must just remember however to set the $max_pages
parameter when you make use of a custom query, otherwise your pagination will break
With a few minor tweaks, your query should look like this
<div id="container">
<div id="content" role="main">
<?php
$btpgid=get_queried_object_id();
$btmetanm=get_post_meta( $btpgid, 'WP_Catid','true' );
$paged = (get_query_var('paged')) ? get_query_var('paged') : 1;
$args = array( 'posts_per_page' => 5, 'category_name' => $btmetanm,
'paged' => $paged,'post_type' => 'post' );
$postslist = new WP_Query( $args );
if ( $postslist->have_posts() ) :
while ( $postslist->have_posts() ) : $postslist->the_post();
echo "<div style='border:2px groove black; margin-bottom:5px;'><h3 class='btposth'>";
the_title();
echo "</h3><div class='btpostdiv'>";
the_content();
echo "</div></div>";
endwhile;
next_posts_link( 'Older Entries', $postslist->max_num_pages );
previous_posts_link( 'Next Entries »' );
wp_reset_postdata();
endif;
?>
</div><!-- #content -->
</div><!-- #container -->
Answered By - Pieter Goosen Answer Checked By - Terry (PHPFixing Volunteer)
0 Comments:
Post a Comment
Note: Only a member of this blog may post a comment.