Skip to content

Commit a78e4e7

Browse files
committed
Return custom product metadata with products for shopkeeper over API.
1 parent 97a2b88 commit a78e4e7

File tree

1 file changed

+65
-1
lines changed

1 file changed

+65
-1
lines changed

wc-api-custom-meta.php

Lines changed: 65 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -3,7 +3,7 @@
33
Plugin Name: WC API Custom Metafields
44
Plugin URI: https://github.com/academe/TBC
55
Description: Allows custom meta fields to be added to products when creating or updating.
6-
Version: 0.5
6+
Version: 0.5.1
77
Author: Jason Judge
88
Author URI: http://academe.co.uk
99
*/
@@ -37,3 +37,67 @@ function academe_wc_api_custom_meta($id, $data) {
3737
}
3838
}
3939

40+
41+
// GET product through the API
42+
add_filter('woocommerce_api_product_response', 'academe_wc_api_get_meta', 10, 4);
43+
44+
function academe_wc_api_get_meta($product_data, $product, $fields, $server) {
45+
// The admin and shop manager will have the capability "manage_woocommerce".
46+
// We only want users with this capability to see additional product meta fields.
47+
48+
if (current_user_can('manage_woocommerce')) {
49+
$product_id = $product->id;
50+
51+
// Meta fields we don't want, due to them being already in the data.
52+
$exclude = array(
53+
// A few WP internal fields should not be exposed.
54+
"_edit_lock",
55+
"_edit_last",
56+
// All these meta fields are already present in the product_data in some form.
57+
"_visibility",
58+
"_stock_status",
59+
"total_sales",
60+
"_downloadable",
61+
"_virtual",
62+
"_regular_price",
63+
"_sale_price",
64+
"_purchase_note",
65+
"_featured",
66+
"_weight",
67+
"_length",
68+
"_width",
69+
"_height",
70+
"_sku",
71+
"_product_attributes",
72+
"_price",
73+
"_sold_individually",
74+
"_manage_stock",
75+
"_backorders",
76+
"_stock",
77+
"_upsell_ids",
78+
"_crosssell_ids",
79+
"_product_image_g
80+
allery",
81+
// The sale dates are actually not directly in the normal data returned.
82+
"_sale_price_dates_from",
83+
"_sale_price_dates_to",
84+
);
85+
86+
$all_meta = get_post_meta($product_id);
87+
88+
// Filter out meta we don't want.
89+
$all_meta = array_diff_key($all_meta, array_flip($exclude));
90+
91+
// Unserialize the meta field data where necessary.
92+
foreach($all_meta as $key => &$value) {
93+
$value = maybe_unserialize(reset($value));
94+
}
95+
unset($value);
96+
97+
$meta = array($all_meta);
98+
99+
$product_data['meta'] = $meta;
100+
}
101+
102+
return $product_data;
103+
}

0 commit comments

Comments
 (0)