Expose Custom Product Fields in the WooCommerce REST API
Adds the product meta fields you list to WooCommerce REST API product responses as a tidy "custom_fields" object, and lets API clients update them.
Opens WPIDE on
Code
$wpide_rest_product_meta = array( '_wpide_subtitle', '_wpide_cost', '_wpide_unit_label' ); // Meta keys to expose.
add_filter( 'woocommerce_rest_prepare_product_object', function ( $response, $product ) use ( $wpide_rest_product_meta ) {
$fields = array();
foreach ( $wpide_rest_product_meta as $key ) {
$fields[ ltrim( $key, '_' ) ] = $product->get_meta( $key );
}
$response->data['custom_fields'] = $fields;
return $response;
}, 10, 2 );
add_action( 'woocommerce_rest_insert_product_object', function ( $product, $request ) use ( $wpide_rest_product_meta ) {
$incoming = $request->get_param( 'custom_fields' );
if ( ! is_array( $incoming ) ) {
return;
}
foreach ( $wpide_rest_product_meta as $key ) {
$name = ltrim( $key, '_' );
if ( array_key_exists( $name, $incoming ) && is_scalar( $incoming[ $name ] ) ) {
$product->update_meta_data( $key, sanitize_text_field( (string) $incoming[ $name ] ) );
}
}
$product->save_meta_data();
}, 10, 2 );
Notes
Only the keys you list are exposed or writable, and API clients still need WooCommerce API keys with the right access.
How to add this snippet
- Install WPIDE on your WordPress site (it is free) and open Code Snippets.
- Use snippet above adds it from the library in one click. Or copy the code into a new snippet with the same code type.
- It is added inactive: review the code and settings, then switch it on.