我已经在附件上启用了类别,我正在尝试实现自动处理“未分类”类别的逻辑,如下所示:
1) 如果附件没有类别,请将其设置为“未分类”
2) 如果附件除了“未分类”之外还有其他类别,请从帖子的类别列表中删除“未分类”
我已经处理了大部分逻辑,但现在我不知道如何从附件中删除类别。这是我的代码:
<?php
// Enable categories with attachments
register_taxonomy_for_object_type( \'category\', \'attachment\' );
if( is_admin() ) {
add_action(\'add_attachment\', \'emt_set_attachment_category\');
add_action(\'edit_attachment\', \'emt_set_attachment_category\');
function emt_set_attachment_category( $post_ID ) {
$attachmentCategories = wp_get_object_terms( $post_ID, \'category\' );
// if attachment has many categories, remove the default category
if (count($attachmentCategories) > 1) {
foreach ($attachmentCategories as $key => $category)
if ($category->name == "Uncategorized")
// How to delete it??
return;
}
// if attachment already have categories, stop here
if (count($attachmentCategories) == 1)
return;
// if attachment has no categories, set default category
wp_set_post_categories( $post_ID, array( get_option(\'default_category\') ) );
}
}
最合适的回答,由SO网友:s_ha_dum 整理而成
你想要的wp_remove_object_terms()
.
if ($category->name == "Uncategorized") {
wp_remove_object_terms( $post_ID, \'uncategorized\', \'category\' );
}
未经测试,但“附件”几乎只是隐藏的帖子,所以我相当肯定这应该会起作用。