wp_delete_object_term_relationships()
云策文档标注
概述
wp_delete_object_term_relationships() 函数用于解除对象与一个或多个分类法之间的关联关系。它会移除对象与指定分类法中所有术语的关系,但不会删除术语或分类法本身。
关键要点
- 函数作用:移除对象与指定分类法中所有术语的关联,不删除术语或分类法。
- 参数:$object_id(整数,必需)为对象ID;$taxonomies(字符串或数组,必需)为分类法名称列表或单个名称。
- 内部实现:通过循环处理每个分类法,调用 wp_get_object_terms() 获取术语ID,再使用 wp_remove_object_terms() 移除关联。
- 相关函数:wp_get_object_terms() 用于获取对象关联的术语,wp_remove_object_terms() 用于移除特定术语关联。
- 使用场景:常用于删除文章、附件或链接时清理分类法关系,如 wp_delete_post() 等函数内部调用。
代码示例
// 删除文章的所有标签关系
$post_id = 55;
wp_delete_object_term_relationships( $post_id, 'post_tag' );
// 删除文章的多个分类法关系
$post_id = 55;
$taxonomies = array( 'category', 'post_tag', 'custom_taxonomy' );
wp_delete_object_term_relationships( $post_id, $taxonomies );
原文内容
Unlinks the object from the taxonomy or taxonomies.
Description
Will remove all relationships between the object and any terms in a particular taxonomy or taxonomies. Does not remove the term or taxonomy itself.
Parameters
$object_idintrequired-
The term object ID that refers to the term.
$taxonomiesstring|arrayrequired-
List of taxonomy names or single taxonomy name.
Source
function wp_delete_object_term_relationships( $object_id, $taxonomies ) {
$object_id = (int) $object_id;
if ( ! is_array( $taxonomies ) ) {
$taxonomies = array( $taxonomies );
}
foreach ( (array) $taxonomies as $taxonomy ) {
$term_ids = wp_get_object_terms( $object_id, $taxonomy, array( 'fields' => 'ids' ) );
$term_ids = array_map( 'intval', $term_ids );
wp_remove_object_terms( $object_id, $term_ids, $taxonomy );
}
}
Changelog
| Version | Description |
|---|---|
| 2.3.0 | Introduced. |
Skip to note 3 content
Codex
Delete all tag relationships for a post
$post_id = 55; wp_delete_object_term_relationships( $post_id, 'post_tag' ); // Post 55 now has no tags.Skip to note 4 content
Codex
Delete multiple taxonomies’ relationships for a post
$post_id = 55; $taxonomies = array( 'category', 'post_tag', 'custom_taxonomy' ); wp_delete_object_term_relationships( $post_id, $taxonomies );