register_taxonomy with multiple object type and update_count_callback

The register_taxonomy accept array as the object type so I can link as many custom post types to a custom taxonomy. That is fine.

The issue is, the default taxonomy count is always zero with the default settings, so what should I set for the argument update_count_callback?

I’ve been thinking of this since, the taxonomy is linked to multiple post types, so the count is meaningful when I am viewing a particular post type.

So, what is the best way to handle custom taxonomy count if this taxonomy is linked to multiple custom post types?

1 Answer
1

Ive run into things similar from time to time. What I’ve ended up doing when using custom post types and taxonomies is the following:

  • Setup a callback on init (before 10) to register taxonomies.
  • Setup another on init (before 10) to register post types.
  • Setup another on 10 to relate them, maybe later if working with other peoples custom taxonomies and post types and they are registering them at 10.

Doing so has almost always eliminated odd issues that I’ve run into with custom objects and the documentation on register_* functions in wordpress notes that you should definitely be registering them during init.

If you do not link them manually, you may or may not get proper talking back and forth between them … and the update_callback_count is part of that talking back and forth, so I register all objects during init before 10 and then associate them all after (or on) 10.

add_action('init', do_create_taxonomies, 7);
function do_create_taxonomies() {
   # setup taxonomies as array of key => options arrays
   foreach ( $taxonomies as $slug => $options ) {
      register_taxonomy("{$slug}", null, "{$options}");
   }
}

add_action('init', do_create_post_types, 8);
function do_create_post_types() {
   # setup post types as array of key => options arrays
   foreach ( $post_types as $slug => $options ) {
      register_post_type("{$slug}", "{$options}");
   }
}

add_action('init', do_bind_post_types_to_taxonomies, 11);
function do_bind_post_types_to_taxonomies() {
   # setup relationships as Tax_slug => array( post_type_slugs )
   foreach ( $relationships as $tax_slug => $post_types ) {
      if ( is_array($post_types) ) {
         foreach ( $post_types as $post_type_slug ) {
            register_taxonomy_for_object_type( "{$tax_slug}", "{$post_type_slug}" );
         }
      } else {
         register_taxonomy_for_object_type("{$tax_slug}", "{$post_types}");
      }
   }
}

That has solved all kinds of strange problems related to custom post types and taxonomies for me. If that doesn’t do the trick, it might be worth digging into the source to see exactly how _update_post_term_count works … and look at your relationships to see if maybe it is forcing _update_generic_term_count instead.

Leave a Comment