wordpress hack for post pagination on static subpages

22. November 2014 - wordpress

Even in the times of wordpress 4.x, problems like  "How do I paginate the posts in my blog correctly ", "… only the first page of my blog is showing…" or "… broken pagination…" turn up in question and answer sites like stackoverflow.com over and over.

Of course, there are lots of tips and answers available. However, none of them solved mine and here is my hack.

Let’s assume, my blog has the url "myhomepage.com/blog". I’m using "nice" permalinks, so the post "mypost" has the url "myhomepage.com/blog/mypost". "blog" is a static subpage with a template file for the code.

The template looks like this:

get_header();
…
global $wp_query;
$orig_query = $wp_query; // save old wp_query
$paged = ( get_query_var('page') ) ? get_query_var('page') : 1; // 'page' because we are on a static page
$args = array(
'category_name' => 'blog',
'paged' => $paged,
'order' => 'DESC'
);
$wp_query = new WP_Query($args);
if ($wp_query->have_posts()) {
while ($wp_query->have_posts()) {
$wp_query->the_post();
//.. do something with the post ..
}
next_posts_link();
previous_posts_link();
} else echo "no post available";
$wp_query =$orig_query;  //restore wp_query
get_footer();

Trying this, I found that all is working well except for the part where get_query_var() comes in. When the blog is called with the initial link "myhomepage.com/blog", get_query_var() is not defined and $paged defaults to 1, which is ok. The first blog's posts appear and next_posts_link() creates the correct link "myhomepage.com/blog/page/2/" for the second page. Alas, using it, get_query_var() is still undefined, and $paged again defaults to 1.

Obviously, get_query_var() can't pull the page number from "myhomepage.com/blog/paged/2/" for reasons I don't now.

So, I decided to lend it a hand:
global $wp_query;
$orig_query = $wp_query;

$pattern = "/\/page\/([0-9]+)\//";
$subject = "$_SERVER[HTTP_HOST]$_SERVER[REQUEST_URI]";     // the url
if (get_query_var('page')) $paged=get_query_var('page');   // give get_query_var() a chance
elseif (preg_match($pattern, $subject, $matches)) $paged=$matches[1]; // otherwise ...
else $paged=1;
...

Now pagination is working, and as we use $wp_query, all advanced pagination plugins that depend on it will work, too.