Wordpress 类别不计算媒体附件

Wordpress category not counting media attachments

在 Wordpress 中,我正在创建一个画廊,它将自动显示来自所选类别及其子类别的新图像。我已经设置了类别,以便它们将适用于使用以下媒体的媒体:

register_taxonomy_for_object_type( 'category', 'attachment' );

现在我需要进行设置,以便类别计算相关附件而不仅仅是帖子。 我发现这个 link 如何使用此代码覆盖类别的默认值 update_count_callback:

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' );

但到目前为止我还没有弄明白(不确定它是否不起作用或者我只是不理解某些东西,比如 'your_new_arg')。 我在注册新分类法时确实找到了 update_count_callback 功能选项,但我不想自己创建,我想将它与现有类别分类法一起使用。

非常感谢对此的任何帮助。谢谢!

希望这对同样遇到此问题的人有所帮助。这就是我最终放入 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' );

我已经测试了 Victoria S 的答案,它正在运行。

如果有人想避免直接操作 WordPress 全局变量,以下解决方案基于原生 WordPress 函数。

function my_add_categories_to_attachments() {
    $myTaxonomy = get_taxonomies(array('name' => 'category'), 'objects')['category'];
    $myTaxonomy->update_count_callback = '_update_generic_term_count';
    register_taxonomy ('category',
                       $myTaxonomy->object_type,
                       array_merge ((array) $myTaxonomy,
                                    array('capabilities' => (array) $myTaxonomy->cap)));

    register_taxonomy_for_object_type( 'category', 'attachment' );
}
add_action( 'init' , 'my_add_categories_to_attachments' );

这里的关键是register_taxonomy is used to recreate the category taxonomy identically, but changing the update_count_callback function. We use the taxonomy object from get_taxonomies赋值给了$myTaxonomy

  • 第一个参数是我们要更改的 Taxonomy slug:'category'
  • 第二个参数是对象 (post) 类型的数组。我们从 get_taxonomies.
  • 返回的对象中使用它
  • 第三个参数 ($args) 是分类法属性的数组。我们必须确保正确包含 $myTaxonomy 中的所有内容,以确保重新创建的 category 与原始的相同,除了我们想要的更改,在这种情况下修改 update_count_callback使用 _update_generic_term_count 而不是默认的 _update_post_term_count。唯一的问题是 capabilities 属性,因为它必须作为 capabilities 传递,但在 Taxonomy 对象中作为 cap 存储,因此我们需要扩展数组$argscap 对象在 capabilities.
  • 的标签下转换为数组

请注意,由于某些原因,在我的测试过程中,我看到重新创建的分类法的 labels 数组与原始分类法相比包含一个额外的项目 (["archives"]=>"All Categories")。这应该不会影响系统,因为任何地方都没有引用的附加标签应该不会引起问题。

您可以使用 var_dump(get_taxonomies(array('name' => 'category'), 'objects')['category']) 轻松比较编辑前后的分类法,以确保一切有序。 (除非您知道自己在做什么,否则不要在生产现场这样做!)