Modifying Wordpress
Posted by Jonathan Ng | Filed under Technical
Don’t let the title fool you, I’m not WordPress “modder”. It’s just that WordPress’ post_nav_link() function needs a little tuning to work properly. According to WordPress’ codex documetation, post_nav_link() displays links for next and previous pages. Useful for providing “paged” navigation of index, category and archive pages.
To display “< View Newer Posts or View Older Posts >“, you simply enter the following wherever you want it the links to appear:
< ?php posts_nav_link(' or ', '< View Newer Posts', 'View Older Posts >'); ?>
If you are at, say page 2 of 3, then the links appear perfectly fine. However, when you are at the first page, you’ll get something like “or View Older Posts >“. Yes, with the “or”. The documentation didn’t mention any tags that would check whether there’s any more pages. A further look into the codes (/wp-includes/template-functions-list.php) confirmed that. If there was one, you could probably do something like this to the Kubrik template:
But then again, there’s no such function. So instead of having that condition check in the template, I moved it into wordpress itself. The post_nav_link() function can be found in wp-includes/template-functions-list.php.
function previous_posts_link($label='« Previous Page') {
global $paged;
if ((! is_single()) && ($paged > 1) ) {
...
return true;
}
return false;
}
function posts_nav_link($sep=' — ', $prelabel='« Previous Page', $nxtlabel='Next Page »') {
global $request, $posts_per_page, $wpdb, $max_num_pages;
if (! is_single()) {
...
if ($max_num_pages > 1) {
if (previous_posts_link($prelabel)) {
echo preg_replace('/&([^#])(?![a-z]{1,8};)/’, ‘&$1′, $sep);
}
next_posts_link($nxtlabel, $max_page, $sep);
}
}
}
The trick is making previous_posts_link() return “flag”. When posts_nav_link() is called, previous_posts_link() is called. It then echoes the link if there’s one (if there’s a previous page). With the modification, it returns true (if there’s a previous page). Program flow returns to posts_nav_link() and the seperator ” or ” is echoed. I’m not good at explaining codes, but the codes are simple enough.