I’m using WooCommerce and want to get the meta keys specifically for the product e.g. price, color and so on…
But the problem is that I don’t want to get all meta keys but only the ones needed. For example I don’t need _edit_last
, _edit_lock
, _wc_review_count
… and just need price
and color
(as an example). If it was a web page that wasn’t important but I don’t want to show them on web page but I want to send them as json to somewhere else. So the data should be filtered. BTW it is in plugin and I want to share it with others so I can’t/shouldn’t access their WooCommerce api.
my code that gets all meta keys (but I want only some of them):
$attributes = get_post_meta($product->get_id());
foreach($attributes as $key => $value) {
$result['products'][$p]['attributes'][$key] = $value[0];
}
and the result of code above is:
[attributes] => Array
(
[_edit_last] => 1
[_edit_lock] => 1594817821:1
.
.
.
)
but I want:
[attributes] => Array
(
[price] => 1000
[color] => 'red'
.
.
.
)
3
Answers
There can be two ways to do this, One is to filter the metadata array manually in the foreach loop and other is to hit a custom query to wp_postmeta table for specific keys.
There is multiple ways depending on what you want:
1). You will need to use
WC_Product
methods on the WC_Product Object to get product properties:2). For specific or custom product meta data, you will use
WC_Data
methodget_data()
using the desired meta key like:3). You can use instead the
WC_Data
methodget_data()
on theWC_Product
object to get unprotected meta data in an array:You will get something like (extract):
Here is Woocommerce Code Reference about how to get metadata from each product.
Also, this is example how to get metadata by key below:
}