0

spent over four hours on this and still hitting a wall, hope StackExchange knows better. :/

Basically, I have some Woo products and whenever a new product is added, its name should be saved as a term of a custom taxonomy I've registered( 'Models' ), but only if it's in a certain product category, let's say the name of the category would be 'Keyboards'.

Now, every time I add a new product, e.g. a keyboard named 'The Best Keyboard' and check the 'Keyboards' term in the product category metabox, 'The Best Keyboard' would also be automatically added as a term to the 'Models' taxonomy (which I need to display compatibilities with various other products). This has been extremely useful in what I'm trying to achieve and I've trimmed the code a bit:

add_action( 'save_post', 'add_custom_terms' );

function add_custom_terms( $post_id ) {
  if ( 'product' === get_post_type( $post_id ) ) {

        $term_title = get_the_title( $post_id );
        $term_slug = get_post( $post_id )->post_name;

        $existing_terms = get_terms( 'compatibility', array(
            'hide_empty' => false
            )
        );

        foreach( $existing_terms as $term ) {
            if ( $term->description === $post_id ) {
                wp_update_term( $term->term_id, 'compatibility', array(
                    'name' => $term_title,
                    'slug' => $term_slug
                    )
                );
                return;
            }
        }

        wp_insert_term( $term_title, 'compatibility', array(
            'slug' => $term_slug,
            'description' => $post_id
            )
        );
    }
}

And it's where I got stuck. It works exactly as it's supposed to, but it always adds the product name to the Models taxonomy, regardless of whether the term 'Keyboards' has been checked or not.

So, my basic question is - how do I set up a conditional for this to happen only when the product is a Keyboard?

From what I've gathered, it also seems that I should be using two hooks, 'save_post' and 'publish_post', as 'save_post' does not know whether the 'Keyboards' checkbox has been checked until after the post/product's been published, thus making it impossible to it as a condition for adding a term to the custom taxonomy, but I honestly don't understand how to combine the two hooks. If anyone can help out - I owe you one!

0

As you say, when triggered 'save_post' the changes are not been mae, so there's not yet an association with a term.

But..in the $_POST['product_cat'] variable you have the array (IDS) of the selected categories, so you can check if the product belongs to the 'Keyboard' category ( based on its ID) and decide whether or not to perform further actions

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.