wordpresscountattachmentcategoriestaxonomy

Wordpress category not counting media attachments


In Wordpress I am creating a gallery that will automatically display new images from a chosen category and its subcategories. I have set up the categories so that they will apply to media using:

register_taxonomy_for_object_type( 'category', 'attachment' );

Now I need to make it so that categories will count the related attachments not just posts. I found this link How to Override default update_count_callback for category with this code:

function change_category_arg() {
    global $wp_taxonomies;
    if ( ! taxonomy_exists('category') )
        return false;

    $new_arg = &$wp_taxonomies['category']->update_count_callback;
    $new_arg->update_count_callback = 'your_new_arg';

}
add_action( 'init', 'change_category_arg' );

But as of yet I have not figured it out (not sure if it doesn't work or if I'm just not understanding something, such as what would be 'your_new_arg'). I did find the update_count_callback function option when registering a new taxonomy but I don't want to make my own, I want to use it with the existing category taxonomy.

Any help with this is much appreciated. Thanks!


Solution

  • Hopefully this helps anyone that also had this problem. This is what I ended up putting in functions.php:

    //Update Category count callback to include attachments
    function change_category_arg() {
        global $wp_taxonomies;
        if ( ! taxonomy_exists('category') )
            return false;
    
        $wp_taxonomies['category']->update_count_callback = '_update_generic_term_count';
    }
    add_action( 'init', 'change_category_arg' );
    
    //Add Categories taxonomy
    function renaissance_add_categories_to_attachments() {
        register_taxonomy_for_object_type( 'category', 'attachment' );
    }
    add_action( 'init' , 'renaissance_add_categories_to_attachments' );