Why get_posts() Bypasses Pagination and How to Fix It
You are encountering a common pitfall in WordPress development: using get_posts() when you actually need a global query that understands pagination state. The core issue isn't your logic for fetching posts or setting the $paged variable; it is the function you chose to retrieve them.
When you call get_posts(), you are invoking a static method that returns an array of WP_Post objects. Crucially, this method does not modify the global $wp_query. It operates in isolation. Because the main query remains untouched, WordPress's template system has no way to know you are on page 2, 3, or beyond. Consequently, when you call next_posts_link() or previous_posts_link(), those functions check the state of the main query ($wp_query) to determine if there are more pages and where they should link. Since the main query still thinks it's on page 1 (or hasn't been queried at all for this archive), the links either fail to generate or redirect back to the homepage.
To get pagination working, you must replace get_posts() with WP_Query. Unlike get_posts(), WP_Query allows you to run a completely independent query that doesn't interfere with the main loop but still interacts with WordPress's global state regarding pagination variables.
Here is how to refactor your code to achieve the desired five posts per page with functional pagination links:
<div id="container">
<div id="content" role="main">
<?php
// Get the category slug from custom field
$btpgid = get_queried_object_id();
$btmetanm = get_post_meta( $btpgid, 'WP_Catid', true );
// Retrieve current page number
$paged = (get_query_var('paged')) ? get_query_var('paged') : 1;
// Configure arguments for WP_Query
$args = array(
'posts_per_page' => 5,
'category_name' => $btmetanm,
'post_type' => 'post',
'orderby' => 'date', // Explicitly ordering by date is often safer for pagination
'order' => 'DESC'
);
// Execute the query
$myposts = new WP_Query( $args );
if ( $myposts->have_posts() ) :
while ( $myposts->have_posts() ) :
$myposts->the_post();
echo "<div style='border:2px groove black; margin-bottom:5px;'>";
echo "<h3 class='btposth'>";
the_title();
echo "</h3>";
echo "<div class='btpostdiv'>";
the_content();
echo "</div>";
echo "</div>";
endwhile;
// These links now work because $wp_query is updated by the sub-query logic in WP_Query
echo paginate_links( array(
'base' => esc_url_raw( get_pagenum_link( 1 ) ),
'format' => '?paged=%#%',
'current' => max( 1, get_query_var('paged') ),
'total' => $myposts->max_num_pages,
) );
// Or use the legacy functions which also rely on global state updates:
// next_posts_link( 'Older Entries');
// previous_posts_link('Newer Entries »');
endif;
// Always reset post data to prevent conflicts with the main loop
wp_reset_postdata();
?>
</div>
</div>
The Critical Difference: Global State vs. Local Arrays
The most significant change here is swapping get_posts() for new WP_Query(). While get_posts() is perfect for fetching a specific set of data to display in a sidebar or a separate container without affecting the main loop, it returns an array that is disconnected from the global $wp_query object. Pagination functions like previous_posts_link() and next_posts_link() rely on properties attached to the global query object (specifically max_num_pages and the current page number).
By using WP_Query, you create a fresh instance of a query object. However, simply instantiating it isn't enough; you must use the while ($query->have_posts()) loop syntax provided by WP_Query. This ensures that the internal logic of WordPress recognizes the query as an active iteration.
Handling Custom Fields and Categories
Your original code attempted to fetch posts based on a custom field (WP_Catid) stored on the page itself. The approach using get_queried_object_id() and get_post_meta() is valid for dynamic content, provided that the slug stored in the meta box matches exactly what is passed to the category_name argument.
Note that category_name expects a category slug (e.g., 'technology'), not an ID. If your custom field stores a numeric ID, you would need to change the argument to 'cat' => $btmetanm. Ensure consistency between how the data is entered in the admin and how it is queried.
Avoiding Common Pitfalls
A frequent mistake when switching to WP_Query is forgetting to call wp_reset_postdata(). Because WP_Query temporarily changes the global $post pointer, failing to reset it can cause your theme's sidebar or other widgets to display the wrong post data (often the last item from your custom query) instead of what they expect.
Another consideration is performance. If you are dealing with high-traffic sites, ensure that category_name queries are cached appropriately or consider using taxonomy meta tables if you find yourself querying by custom fields excessively. In most standard scenarios, however, the overhead of a single WP_Query instance is negligible.
If you need further assistance with complex query structures or want to explore how similar logic applies in other PHP frameworks like Laravel (where you might handle pagination differently using Eloquent relationships), check out resources at https://laravelcompany.com.