WordPress > Optimizing a query to show recent posts with a "View All" link when postcount exceeds ma

Posted by Scott B on Stack Overflow See other posts from Stack Overflow or by Scott B
Published on 2010-03-25T18:47:03Z Indexed on 2010/03/25 18:53 UTC
Read the original article Hit count: 488

Filed under:
|

I have a setting in my theme that allows the site owner to set the maximum number of posts ($maxPosts) to display in a "Recent Posts" menu. I'm using a custom script to generate the recent posts (because the Recent Posts widget does not highlight the current page, which I need for my css).

My menu also is set up to display a "View All" link below the post listing, but only if the actual post count is > $maxposts

I'm trying to work out the best method for getting the post count and comparing it to $maxposts in order to determine whether or not to show a "View All" link.

I'm sure there's probably a better way, but here's my code. I'm looking to optimize it to support very large post counts...

$cat=get_cat_ID('excludeFromRecentPosts'); 
$catHidden=get_cat_ID('hidden');
$myquery = new WP_Query();
$myquery->query(array(
    'cat' => "-$cat,-$catHidden",
    'post_not_in' => get_option('sticky_posts')
));
$myrecentpostscount = $myquery->found_posts;
if ($myrecentpostscount > 0) 
{
//show the menu

if ($myrecentpostscount > $maxPosts)
{
//show "View All" link
}
}

I really only need to determine if the total post count from the query is greater than the maxPost setting in order to determine whether to show the "View All" link, so I'm wondering if, in the case there are thousands of posts matching the criteria, to avoid performance issues, I don't need to get a count of all of them. I just need to count up until the point of maxPosts + 1, and that's where I'm struggling a bit because the user could elect to make maxPosts = -1 which means they want to show all posts. But this would be impractical, so I would probably set a upper limit of 20...

© Stack Overflow or respective owner

Related posts about php

Related posts about Wordpress