I want to display the number of posts within a specific category (or categories). In my template I have the following code:
//Get categories from custom field on page, Categories are separated with ','
$categories = explode(",", get_post_meta($post->ID, 'category_id', true));
// Use only the first category in this page template
$cat= 'cat=' . $categories[0];
// Get current page. Is used for pagination.
$page = (get_query_var('paged')) ? get_query_var('paged') : 1;
//Get the posts for selecteed categories
query_posts("$cat&paged=$page&orderby=title&order=ASC"); // &posts_per_page=-1&paged=$page'); // run the query
//Get post count
$post_count = get_post_count($categories, $wpdb);
echo 'Antall artikler: ' . $post_count;
In query.php file I have created the function get_post_count($categories, $wpdb).
The following code returns a result:
function get_post_count($categories, $wpdb) {
$querystr = "
SELECT count(*)
FROM $wpdb->posts
WHERE $wpdb->posts.post_status = 'publish'
";
$result = $wpdb->get_var($querystr);
return $result;
}
But it returns too many posts.
I've tried using the following code:
SELECT count(*)
FROM wp_posts
LEFT JOIN wp_term_relationships ON (wp_posts.ID = wp_term_relationships.object_id)
LEFT JOIN wp_term_taxonomy ON (wp_term_relationships.term_taxonomy_id = wp_term_taxonomy.term_taxonomy_id)
WHERE wp_posts.post_status = 'publish'
AND $wpdb->posts.post_type = 'post'
AND wp_term_taxonomy.term_id IN (15)
But this doesn't return anything at all. I've read a lot of different posts in here, but no one seems to have the answer.
Has anyone managed to count the posts for a specific category?
Cheers!