1

I am trying to unset a category if another category is unset.

First i have a function that add's category if another category is set such as:

function add_category_automatically($post_ID) {
    global $wpdb;
    if ( in_category('3152') ) {
        $cat = array(1208);
        wp_set_object_terms($post_ID, $cat, 'category', true);
    }
}

add_action('save_post', 'add_category_automatically');

This adds category with id 1208 if post has category with id 3152.

Now i need a function that does the exact reverse, that if category with id 3152 is unset i need the function to also unset category with id 1208.

I understand i could simply do something like this, but it will screw things up because i want the end user to be able to set category with id 1208 by itself, it should only be removed if category with id 3152 is removed.

function remove_category_automatically($post_ID) {
    global $wpdb;
    if ( !in_category('3152') ) {
        $cat = array(1208);
        wp_remove_object_terms($post_ID, $cat, 'category', true);
    }
}

add_action('save_post', 'remove_category_automatically');

Thus this code above doesn't work because with this code you cannot set category 1208 by it self, it will always remove 1208 unless 3152 is present, i want some posts to have category 1208 without having cat 3152.

So i try something like this but it's not really working.

function on_all_status_transitions( $new_status, $old_status, $post ) {
    if ( in_category('3152') ) {
        if ( $new_status != $old_status && has_category('3152') ) {
            $cat = array(3152);
            wp_remove_object_terms($post_ID, $cat, 'category', true);
        }
    }
}

add_action( 'transition_post_status', 'on_all_status_transitions', 10, 3 );

Any ideas how to solve this would be greatly appreciated.

  • What hook are you using for this? – Krzysiek Dróżdż Jul 14 '18 at 9:56
  • added the hooks i used for the code in the original post – karnehe Jul 14 '18 at 10:02
1

You can use the deleted_term_relationships action to check if some term is removed from a post object.

This hook is in the wp_remove_object_terms()

function custom_remove_category( $object_id, $tt_ids, $taxonomy ) {
    if( $taxonomy == 'category' ) {
        if( in_array( 3152, $tt_ids ) ) {
            wp_remove_object_terms( $object_id, [1208], 'category' );
        }
    }
    return $object_id;
}
add_action( 'deleted_term_relationships', 'custom_remove_category', 10, 3 );

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.