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!
Hopefully this helps anyone that also had this problem. This is what I ended up putting in functions.php:
I’ve tested the answer from Victoria S and it is working.
But, if someone would like to avoid direct manipulation of WordPress globals, the below solution is based on native WordPress functions.
The key here is that
register_taxonomy
is used to recreate thecategory
taxonomy identically, but changing theupdate_count_callback
function. We use the taxonomy object fromget_taxonomies
assigned to$myTaxonomy
.'category'
get_taxonomies
.$args
) is an array of the properties of the Taxonomy. We have to make sure to include everything properly from$myTaxonomy
, to make sure the recreatedcategory
is identical to the original one, except for the changes we want, in this case modify theupdate_count_callback
to use_update_generic_term_count
instead of the default_update_post_term_count
. The only issue is with thecapabilities
property, as it must be passed ascapabilities
, but is stored in the Taxonomy object ascap
, therefore we need to extend the array of$args
with thecap
object cast as an array under the label ofcapabilities
.Please note, that for some reasons during my tests I saw the
labels
array of the recreated Taxonomy to include one additional item (["archives"]=>"All Categories"
) compared to the original. This should not affect the system, as an additional label not referenced anywhere should not cause issues.You can easily compare the Taxonomy before and after editing to make sure everything is in order by using
var_dump(get_taxonomies(array('name' => 'category'), 'objects')['category'])
. (Do not do that on production site unless you know what you are doing!)