据我所知,这就是你想要实现的目标:
如果将帖子分配给子类别,则将其删除,并在该帖子的类别列表中仅显示其父类别。
您可以使用以下代码为任何子类别实现这一点:
add_filter(\'get_the_terms\', function($terms, $postId, $taxonomy) {
// Return early if not a category, there is an error, or we are on the dashboard.
if(\'category\' !== $taxonomy || is_wp_error($terms) || is_admin()) {
return $terms;
}
// Create an array that will hold only parent categories
$parents = [];
// Loop on all the terms, keep the parents or get the parent of any child
foreach ($terms as $term) {
// This is a parent, add it and continue
if(! $term->parent) {
$parents[$term->term_id] = $term;
continue;
}
// This is a child get its parent and add it
$parent = get_term($term->parent, $taxonomy);
if(is_a($parent, \'WP_Term\')) {
$parents[$parent->term_id] = $parent;
}
}
// Finally, reset the array keys and return it
return array_values($parents);
}, 10, 3);
但是,如果只想对选定的子类别列表执行此操作,请使用以下代码:
add_filter(\'get_the_terms\', function($terms, $postId, $taxonomy) {
// Return early if not a category, there is an error, or we are on the dashboard.
if(\'category\' !== $taxonomy || is_wp_error($terms) || is_admin()) {
return $terms;
}
// Categories to exclude
$excludedIds = [31, 32, 33, 34, 35, 36, 37, 38, 96];
// Create an array that will hold only not excluded categories
$categoriesToKeep = [];
// Loop on all the terms, and replace the excluded categories with their parents
foreach ($terms as $term) {
// This is not in the excluded list, add it and continue
if(! in_array($term->term_id, $excludedIds)) {
$categoriesToKeep[$term->term_id] = $term;
continue;
}
// This an excluded category, replace it with its parent
$parent = get_term($term->parent, $taxonomy);
if(is_a($parent, \'WP_Term\')) {
$categoriesToKeep[$parent->term_id] = $parent;
}
}
// Finally, reset the array keys and return it
return array_values($categoriesToKeep);
}, 10, 3);