How can I make a function inverse to wp_set_post_terms() so that the post is unlinked from the desired taxonomy?

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.

How useful is the publication?

Click on a star to rate it!

Average score 5 / 5. Number of grades: 1

No ratings yet. Rate it first.

Similar posts

How to transfer a site from dle to WordPress?

Transferring a website from DLE (DataLife Engine) to WordPress can be a complex process, especially if the site has a lot of content. Here’s a step-by-step guide: 1. Preparation 2. Export Data from DLE DLE uses its own database structure, so you’ll need to export data and convert it into a format compatible with WordPress:…
Read more