Guest User

Untitled

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