-
Notifications
You must be signed in to change notification settings - Fork 0
/
stock_extra_fields.php
66 lines (59 loc) · 1.95 KB
/
stock_extra_fields.php
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
<?php
// Add Variation Settings
add_action('woocommerce_product_after_variable_attributes', 'variation_settings_fields', 10, 3);
// Save Variation Settings
add_action('woocommerce_save_product_variation', 'save_variation_settings_fields', 10, 2);
// Create new fields for variations
function variation_settings_fields($loop, $variation_data, $variation)
{
global $wpdb;
$table_name = "{$wpdb->prefix}wc_warehouse";
$warehouses = $wpdb->get_results("SELECT code, name FROM $table_name ORDER BY public ASC, sort ASC");
foreach ($warehouses as $warehouse) {
$code = stripslashes($warehouse->code);
$name = stripslashes($warehouse->name);
$key = $variation->ID . '_'. $code;
woocommerce_wp_text_input(
array(
'id' => '_warehouse[' . $key .']',
'label' => _('Warehouse:') . ' ' . $name,
'placeholder' => '',
'description' => '',
'value' => get_post_meta(
$variation->ID,
'warehouse_' . $code,
true
),
'custom_attributes' => array(
'step' => 'any',
'min' => '0'
)
)
);
}
}
// Save new fields for variations
function save_variation_settings_fields($post_id)
{
global $wpdb;
$table_name = "{$wpdb->prefix}wc_warehouse";
$warehouses = $wpdb->get_results("SELECT code FROM $table_name ORDER BY public ASC, sort ASC");
$stock = 0;
foreach ($warehouses as $warehouse) {
$code = stripslashes($warehouse->code);
$key = $post_id . '_'. $code;
$number_field = $_POST['_warehouse'][ $key ];
if ($number_field === '') {
$number_field = 0;
}
$stock += $number_field;
update_post_meta(
$post_id,
'warehouse_' . $code,
esc_attr($number_field)
);
}
$variation = new WC_Product_Variation($post_id);
$variation->set_stock_quantity($stock);
$variation->save();
}