John Davidson

php - Woocommerce attributes are somehow added again after removing them in the save_post_product hook

0 comments
Message:


I have a validating function to remove invalid terms from the product after saving.
my problem is that after I successfully removed the invalid terms.
they are re-added so when the update is complete.
the invalid terms are still saved to the post.


add_action('save_post_product','validate_product',99,3);

function validate_product($product_id,$post,$update){
$store_tax = 'pa_store';
if(get_field('requires_medical_license',$product_id) === true){
$stores = wc_get_product_term_ids($product_id,$store_tax);
$invalid_stores = [];
foreach($stores as $store){
if(get_field('store_type',$store)!=='pharmacy'){
$invalid_stores[] = $store;
}
}
if(!empty($invalid_stores)){
remove_action('save_post_product','validate_product');
$success = wp_remove_object_terms($product_id,$invalid_stores,$store_tax);
add_action('save_post_product','validate_product',99,3);
$after_stores = wc_get_product_term_ids($product_id,$store_tax);
// $success // true
// var_dump($after_stores) // does not contain any invalid stores
// wp_die() // if I stop the execution here, the terms are successfully removed.
}
}
}


My Answer:
It seems like the issue might be related to the timing of when the attributes are being added back after you have removed them in your `validate_product` function.

One possible solution could be to hook into a different action that occurs after the product has been saved and all changes have been finalized. You could try using the `woocommerce_process_product_meta` action instead of `save_post_product`.

Here is an example of how you could modify your code to use the `woocommerce_process_product_meta` action:

php
add_action('woocommerce_process_product_meta','validate_product',99,2);

function validate_product($product_id, $post){
$store_tax = 'pa_store';
if(get_field('requires_medical_license',$product_id) === true){
$stores = wc_get_product_term_ids($product_id,$store_tax);
$invalid_stores = [];
foreach($stores as $store){
if(get_field('store_type',$store)!=='pharmacy'){
$invalid_stores[] = $store;
}
}
if(!empty($invalid_stores)){
$success = wp_remove_object_terms($product_id,$invalid_stores,$store_tax);
}
}
}


By using the `woocommerce_process_product_meta` action, you can ensure that your validation function runs after the product has been saved and all changes have been finalized. This should prevent the invalid terms from being re-added after you have removed them.

I hope this helps! Let me know if you have any other questions.

Rate this post

4 of 5 based on 8700 votes

Comments




© 2024 Hayatsk.info - Personal Blogs Platform. All Rights Reserved.
Create blog  |  Privacy Policy  |  Terms & Conditions  |  Contact Us