3

This is the first time I've attempted to write an action hook.

My CPT has 4 categories. I'm trying to make WP automatically sends an email notification when the category is changed.

By change I mean: Let's say the post has a category of "cat1". The admin unselects cat1 and selects "cat2" and then clicks the "Update" button. I am not talking about overwriting or appending new categories to the list.

My code thus far:

add_action('set_object_terms','email_when_category_changes');

function email_when_category_changes(){
       wp_mail( 'wp@mydomain.com', 'Update on CI board', 'the category changed' );
}

The idea here being that the author will get an email notifying them that their post has been changed from cat1 to cat2.

The code above works in the sense that it sends an email when I click "Update". However, the problem is that it sends an email no matter what I do. Anytime I click "Update", whether anything changed or not, it sends the email.

I thought set_object_terms would only fire if the category was changed. Obviously I'm missing an important concept here. Can anyone help?

  • Have you already tried to narrow this down? Checks like "get original taxonomy terms vs. get new terms"? – kaiser Mar 13 '15 at 16:31
  • I've been Googling and searching this site with every keyword combination I can think of. That's how I got to this point :) I just searched your suggestion and I'm sifting through the results now. – danzo Mar 13 '15 at 16:39
3

Use the hooks added_term_relationship and deleted_term_relationships. These only fire when the relationship changes, as opposed to set_object_terms which always fires:

function wpse_181090_object_terms_updated( $object_id ) {
    static $did = array(); // This function might fire multiple times for the same object, ensure it only runs once

    if ( ! isset( $did[ $object_id ] ) ) {
        $did[ $object_id ] = true;

        // Your notification code
    }
}

add_action( 'deleted_term_relationships', 'wpse_181090_object_terms_updated' );
add_action( 'added_term_relationship',    'wpse_181090_object_terms_updated' );
  • Actually, I spoke too soon... The problem now is that the notification email shows the previous category. If it's cat1 and admin changes it to cat2 and clicks update, the email says cat1. These actions are supposed to fire after the term is added/deleted, so I don't get why they're showing the previous category? – danzo Mar 16 '15 at 20:48
  • @TheDeadMedic Do you know how to prevent from emailing again if added to new category? wordpress.stackexchange.com/questions/216215/… – JediTricks007 Jan 31 '16 at 3:33

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.