[wp-hackers] How can I filter on post count for categories?

Autre Monde autremonde75 at gmail.com
Thu Jun 4 08:32:53 GMT 2009


I guess I haven't explained clearly enough my requirement... ;)

Anyway, thanks a lot for your help Austin, you put me on the right path. I
managed to find a solution. I have registered another taxonomy association
with this piece of code :
1/ The hook :
add_action('init','wats_register_taxonomy',0);
2/ The registration :
function wats_register_taxonomy()
{
  register_taxonomy( 'category', 'ticket', array('hierarchical' => true,
'update_count_callback' => 'wats_update_ticket_term_count', 'label' =>
__('Categories'), 'query_var' => false, 'rewrite' => false) ) ;
}
3/ The update count callback :
function wats_update_ticket_term_count($terms)
{
 global $wpdb;

 foreach ((array) $terms as $term)
 {
        $count = $wpdb->get_var($wpdb->prepare("SELECT COUNT(*) FROM
$wpdb->term_relationships, $wpdb->posts WHERE $wpdb->posts.ID =
$wpdb->term_relationships.object_id AND post_status = 'publish' AND
(post_type = 'ticket' OR post_type = 'post') AND term_taxonomy_id = %d",
$term));
        $wpdb->update($wpdb->term_taxonomy, compact('count'),
array('term_taxonomy_id' => $term));
    }
}

Believe it or not, it works! ;)

I spent the whole day yesterday digging into the core to try to understand
how this count was updated...

So thanks a lot for your help and expertise, much appreciated!
2009/6/4 Austin Matzko <if.website at gmail.com>

> On Thu, Jun 4, 2009 at 1:23 AM, L'Autre Monde<autremonde75 at gmail.com>
> wrote:
> > Ok so I looked at this. My issue isn't really to count the number of
> items
> > but rather to have my count took into consideration. I haven't managed to
> > plug on a place where I can modify on the fly the number when a page
> > containing the category list widget is generated.
>
> I guess I misunderstood what you're trying to do.  If you're talking
> about the category widget that prints wp_dropdown_categories(), you'll
> need to redefine that widget with wp_dropdown_categories() such that
> its "hide_empty" argument is set to 0.
>
> The reason is that by default "hide_empty" is true, meaning that only
> those categories will show up that have a positive count of associated
> objects.  For each taxonomy, that count gets incremented by a callback
> as determined when the taxonomy is defined.  For example, the
> "category" taxonomy for object_type "post" calls
> "_update_post_term_count" as the "update_count_callback."  Since each
> taxonomy specifies its object type and you're using a custom object
> type, probably there is no associated "update_count_callback," and the
> count stays at zero.
>  _______________________________________________
> wp-hackers mailing list
> wp-hackers at lists.automattic.com
> http://lists.automattic.com/mailman/listinfo/wp-hackers
>


More information about the wp-hackers mailing list