Need a function call that is designed solely to get the count of posts matching a criteria. I believe the get_posts() function is too expensive for this operation. I'm merely trying to decide whether or not to show a "View More Posts" link when there are a predefined number of posts to display...
For example, the default number of post links to display is 3. I only want to show a "View More Posts" link if the total number of posts exceeds 3.
Here's my code...
$cat1=get_cat_ID('test');
$cat2=get_cat_ID('test2');
$myposts = get_posts(array('cat' => "$cat1,-$cat2",'showposts' => 3));
$myposts2 = get_posts(array('cat' => "$cat1,-$cat2"));
$mypostcount = count($myposts2);
foreach($myposts as $idx=>$post)
?>
<li><a>Post Info Goes here</a></li>
<?php
if ($mypostscount > 3){ ?>Show View All Link<?php ?>
You're question wasn't completely clear, so here's two methods.
First, if the user is viewing a category page and you want to display this information, you can simply use the following:
That will return the number of posts found for the last query.
If you want to count the number of posts for each category, say for like a homepage I would go about it simply through PHP/MySQL. Here's an example:
I just tested it and it worked properly. Once you get the return from the query just simply grab the row and then do as follows:
or whatever you like with the data. All you need to do to change categories is simply change the last WHERE clause's term_id
Change 13 to the cat you would like to count.
If you would instead like to do it by category name you could change the last part from
to
The first one will select from multiple categories, the second from only one. Hope this helps,
As of wordpress 2.5 a function exists for this: http://codex.wordpress.org/Function_Reference/wp_count_posts
If you don't trust it, use a $wpdb query or PHP/MySQL without the wordpress wrapper
You can do a custom WP_Query in which you use a filter on
posts_fields
to change what is returned by the query. So use WP_Query as you normally would to get the specific list of posts that you're after and change the fields that are pulled to get theCOUNT(wp_posts.ID)
.Also make sure you change posts_per_page to
-1
so that you get all posts.But, also, as noted above by David, the query objects will have the found_posts member that will tell you how many total posts matched the criteria. So your solution may be to use full WP_Query objects instead of using get_posts to get your list.