The wp_set_post_terms()
function allows you to assign terms to a post within a specific taxonomy. To detach a post from a taxonomy, you can use the same function but pass an empty array as the list of terms.
Example:
wp_set_post_terms( $post_id, [], 'taxonomy_name' );
Here:
$post_id
is the ID of the post you want to detach from the taxonomy.taxonomy_name
is the name of the taxonomy from which you want to detach the post.
Detailed Explanation
When you pass an empty array to wp_set_post_terms()
, WordPress removes all associations between the post and the specified taxonomy. This works for any registered taxonomy (both custom and default ones like category
or post_tag
).
Example function to remove terms:
If you need a universal function to remove all terms from a specified taxonomy for a given post:
function remove_post_terms( $post_id, $taxonomy ) {
if ( taxonomy_exists( $taxonomy ) ) {
wp_set_post_terms( $post_id, [], $taxonomy );
} else {
return new WP_Error( 'invalid_taxonomy', 'The specified taxonomy does not exist.' );
}
}
Usage:
remove_post_terms( 123, 'category' ); // Removes all categories from the post with ID 123
remove_post_terms( 456, 'custom_taxonomy' ); // Removes all terms from the custom taxonomy 'custom_taxonomy'
Additional Notes
- Make sure the specified taxonomy is registered and associated with the post type.
- If you only want to remove specific terms, you can pass an array of term IDs that should remain attached to the post.