<?php

	function fix_term_count($terms, $taxonomies, $args) { # {{{
		# Currently, when get_terms is used with a custom taxonomy, it returns
		# a count value that includes unpublished content. So wp_tag_cloud will
		# produce unexpected results. The tooltip will show the count including
		# unpublished content, but the page it links to will only show published
		# items. If a term is only attached to unpublished content, then it'll
		# be a 404, which is even worse. So this filter does its own query to
		# get an accurate count and filters things accordingly.

		# This may be unnecessary in a future WordPress version.

		if (!$args['fix_counts'])
			return $terms;

		global $wpdb;

		$term_ids = array();
		foreach ($terms as $term)
			$term_ids[] = $term->term_id;

		$posts_where = "AND $wpdb->posts.post_type != 'revision' AND (($wpdb->posts.post_status = 'publish') OR ($wpdb->posts.post_status = 'inherit' AND (p2.post_status = 'publish')))";
		$posts_where = apply_filters('posts_where', $posts_where);

		$query = "
			SELECT COUNT(1) as count, t.term_id
				FROM $wpdb->terms AS t
				INNER JOIN $wpdb->term_taxonomy AS tt ON t.term_id = tt.term_id
				INNER JOIN $wpdb->term_relationships AS tr ON tt.term_taxonomy_id = tr.term_taxonomy_id
				INNER JOIN $wpdb->posts ON $wpdb->posts.ID = tr.object_id
				LEFT JOIN $wpdb->posts AS p2 on $wpdb->posts.post_parent = p2.ID
				WHERE t.term_id IN (".join(', ', $term_ids).")
					$posts_where
				GROUP BY t.name, t.term_id, tt.parent
				";

		$counts = $wpdb->get_results($query);
		$_terms = array();
		$_counts = array();
		foreach ($counts as $c)
			$_counts[$c->term_id] = $c->count;

		foreach ($terms as $t) {
			if (!$_counts[$t->term_id]) {
				if ($args['hide_empty'])
					continue;
				$t->count = 0;
			} else {
				$t->count = $_counts[$t->term_id];
			}
			$_terms[] = $t;
		}

		# TODO: Worry about hierarchy and padding parent counts or just be
		# satisifed knowing that I didn't set up any of my taxonomies as
		# hierarchical?

		return $_terms;
	} # }}}

# vim:noet:ts=4
