Time Until Wedding
Days
Hours
Minutes
Seconds
 
Navigation
 
Search
 
My Usable Projects
 
Reading...
 
Listening...
 
Random Image
Reception (55)
 
Archives
 
Me. Elsewhere.
 
Feeds and Such

Google Reader or Homepage
Add to My Yahoo!
Add to Technorati Favorites!
Bookmark del.icio.us
Bookmark Furl
Bookmark Spurl
 
Darcy
 
Things I Like
Get Songbird
 
License
 
WordPress: more_posts, old_posts, new_posts

I just scratched an itch I’ve had for a long time. I always hate how on my category pages and my archive pages the little “More Posts” box would display even if there were no posts. Also, I could never check and see if there were no “Newer” or no “Older” posts so I could still print the words out in non-link form.

I finally did something about it today. I started by looking through the codex, and finding nothing. So I started digging through the WP code looking for the posts_nav_link() which sorta did what I wanted, but just echoed to the page instead of returning. I found it in wp-includes/template-functions-links.php and started chopping it up.

In the end I came up with three functions for my ‘my-hacks.php’ file. I didn’t want to spend the time making it into a plugin since it’s not that big a deal. They aren’t terribly efficient, but they work and thats what matters. Also, I pre-pended jh to the function names so there wouldn’t be any chance of collisions.

Returns true if there are more posts, newer or older.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
function jh_more_posts() {
  global $paged, $result, $request, $posts_per_page, $wpdb, $max_num_pages;
	if ( isset($max_num_pages) ) {
		$max_page = $max_num_pages;
	} else {
		preg_match('#FROM\s(.*)\sGROUP BY#siU', $request, $matches);
		$fromwhere = $matches[1];
		$numposts = $wpdb->get_var("SELECT COUNT(DISTINCT ID) FROM $fromwhere");
		$max_page = $max_num_pages = ceil($numposts / $posts_per_page);
	}
	if( !$paged )
	  $paged = 1;
	if($paged == 1 && $paged == $max_page)
	  return false;
	else
	  return true;	
}

Returns true if there are more ‘older’ posts.

1
2
3
4
5
6
7
function jh_more_old() {
  global $paged;
	if( !$paged  || $paged == 1)
	  return true;	
	 else
	  return false;
}

Returns true if there are more ‘newer’ posts.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
function jh_more_new() {
  global $paged, $result, $request, $posts_per_page, $wpdb, $max_num_pages;
	if ( isset($max_num_pages) ) {
		$max_page = $max_num_pages;
	} else {
		preg_match('#FROM\s(.*)\sGROUP BY#siU', $request, $matches);
		$fromwhere = $matches[1];
		$numposts = $wpdb->get_var("SELECT COUNT(DISTINCT ID) FROM $fromwhere");
		$max_page = $max_num_pages = ceil($numposts / $posts_per_page);
	}
	if( !$paged )
	  $paged = 1;
	if($paged == $max_page)
	  return true;
	else
	  return false;	
}

Posted January 24th, 2007 - Permalink
Categories: PHP - Programming - Snippets - Wordpress
You can leave a comment, or trackback from your own site.
 
Adjacent Posts
 
Comments