Guest User

Untitled

a guest
Apr 23rd, 2018
82
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 2.27 KB | None | 0 0
  1. add_action( 'save_post_product', 'auto_add_product_attributes', 50, 3 );
  2. function auto_add_product_attributes( $post_id, $post, $update ) {
  3.  
  4. ## --- Checking --- ##
  5.  
  6. // Exit if it's an autosave
  7. if ( defined( 'DOING_AUTOSAVE' ) && DOING_AUTOSAVE )
  8. return $post_id;
  9.  
  10. // Exit if it's an update
  11. if( $update ){
  12. update_post_meta( $post_id, '_updating', 'YES' );
  13. return $post_id;
  14. } else {
  15. update_post_meta( $post_id, '_updating', 'NO' );
  16. }
  17.  
  18. // Exit if user is not allowed
  19. if ( ! current_user_can( 'edit_product', $post_id ) )
  20. return $post_id;
  21.  
  22. ## --- The code --- ##
  23.  
  24. global $wpdb;
  25.  
  26. // Get all existing product attributes
  27. $attributes = $wpdb->get_results( "SELECT * FROM {$wpdb->prefix}woocommerce_attribute_taxonomies" );
  28.  
  29. $position = 0; // Auto incremented position value starting at '0'
  30. $visible = ''; // can be: '' or '1'
  31. $variation = ''; // can be: '' or '1'
  32. $data = array(); // initialising (empty array)
  33.  
  34. foreach( $attributes as $attribute ){
  35. // Get the correct taxonomy for product attributes
  36. $taxonomy = 'pa_'.$attribute->attribute_name;
  37. $attribute_id = $attribute->attribute_id;
  38.  
  39. // Get all term Ids values for the current product attribute (array)
  40. $term_ids = get_terms(array('taxonomy' => $taxonomy, 'fields' => 'ids'));
  41.  
  42. // Get an empty instance of the WC_Product_Attribute object
  43. $product_attribute = new WC_Product_Attribute();
  44.  
  45. // Set the related data in the WC_Product_Attribute object
  46. $product_attribute->set_id( $attribute_id );
  47. $product_attribute->set_name( $taxonomy );
  48. $product_attribute->set_options( $term_ids );
  49. $product_attribute->set_position( $position );
  50. $product_attribute->set_visible( $visible );
  51. $product_attribute->set_variation( $variation );
  52.  
  53. // Add the product WC_Product_Attribute object in the data array
  54. $data[$taxonomy] = $product_attribute;
  55.  
  56. $position++; // Incrementing position
  57. }
  58. // Get an instance of the WC_Product object
  59. $product = wc_get_product( $post_id );
  60.  
  61. // Set the array of WC_Product_Attribute objects in the product
  62. $product->set_attributes( $data );
  63.  
  64. $product->save(); // Save the product
  65. }
Add Comment
Please, Sign In to add comment