Update term count using a callback function

I think I’ve worked this out. First of all, you need to define your taxonomy. I’m pulling this code directly from the codex; however, I’ve added one parameter update_count_callback. I’ve set this to the cleverly titled my_update_count_callback. This just specifies that when a post of type post (this will be whatever CPTs you associate the taxonomy with) is added or updated, this function will be executed instead of the normal routine for updating the count. The taxonomy is registered with:

add_action('init', 'add_taxonomy');
function add_taxonomy()
{
    // Add new taxonomy, make it hierarchical (like categories)
    $labels = array(
        'name' => _x( 'Genres', 'taxonomy general name' ),
        'singular_name' => _x( 'Genre', 'taxonomy singular name' ),
        'search_items' =>  __( 'Search Genres' ),
        'all_items' => __( 'All Genres' ),
        'parent_item' => __( 'Parent Genre' ),
        'parent_item_colon' => __( 'Parent Genre:' ),
        'edit_item' => __( 'Edit Genre' ),
        'update_item' => __( 'Update Genre' ),
        'add_new_item' => __( 'Add New Genre' ),
        'new_item_name' => __( 'New Genre Name' ),
        'menu_name' => __( 'Genre' ),
    );

    register_taxonomy(
        'genre',
        array('post'),
        array(
            'hierarchical' => true,
            'labels' => $labels,
            'show_ui' => true,
            'query_var' => true,
            'rewrite' => array( 'slug' => 'genre' ),
            'update_count_callback' => 'my_update_count_callback'
        )
    );
}

That’s the straight forward part. Next, I defined the callback. Note that this callback will take two parameters terms (the term ids associated with the CPT) and taxonomy (the name of the taxonomy). The normal update function is defined in taxonomy.php around line 2435. If you have a specified callback, it will run that routine and not the normal one. For my function below, I have simply modified the normal code.

function my_update_count_callback($terms, $taxonomy)
{
    global $wpdb;
    foreach ( (array) $terms as $term)
    {
        do_action( 'edit_term_taxonomy', $term, $taxonomy );

        // Do stuff to get your count
        $count = 15;

        $wpdb->update( $wpdb->term_taxonomy, array( 'count' => $count ), array( 'term_taxonomy_id' => $term ) );
        do_action( 'edited_term_taxonomy', $term, $taxonomy );
    }
}

All you need to do is write your routines for getting your count and then update the count. Note that I left in the two do_action calls as the normal function allows for code to be injected here. I think it’s important to leave those in there so that your plugin won’t cause other ones to malfunction.

Leave a Comment