Wordpress 类别不包括媒体附件

问题描述 投票:0回答:2

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

register_taxonomy_for_object_type( 'category', 'attachment' );

现在我需要这样做,以便类别能够计算相关附件而不仅仅是帖子。 我找到了这个链接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' );

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

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

php wordpress categories attachment taxonomy
2个回答
5
投票

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

1
投票

我已经测试了 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
用于以相同方式重新创建
category
分类法,但更改
update_count_callback
函数。我们使用
get_taxonomies
中的分类对象分配给
$myTaxonomy

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

请注意,由于某些原因,在我的测试过程中,我看到重新创建的分类法的

labels
数组与原始分类法相比包含一项附加项目 (
["archives"]=>"All Categories"
)。这不会影响系统,因为任何地方都没有引用的附加标签不会导致问题。

您可以使用

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

最新问题
© www.soinside.com 2019 - 2025. All rights reserved.