Skip to content

Instantly share code, notes, and snippets.

@barryhughes
Last active May 12, 2023 13:44
Show Gist options
  • Save barryhughes/62176061ec8192000a8cd032392ed58a to your computer and use it in GitHub Desktop.
Save barryhughes/62176061ec8192000a8cd032392ed58a to your computer and use it in GitHub Desktop.
Alter the wp-json/wc/store/v1/products/<ID> response so that it includes 'more complete' information about variations.
<?php
/**
* Modify /wp-json/wc/store/v1/products/<ID> so that it returns more complete data about each variation.
*
* Not extensively tested, just captures an idea about how we might do this.
*/
add_filter( 'rest_request_after_callbacks', function ( $response, $handler, $request ) {
// If this is not a Store API product request, do not interfere.
if ( ! str_starts_with( $request->get_route(), '/wc/store/v1/products/' ) || $request->get_method() !== 'GET' ) {
return $response;
}
// Determine the product ID, or bail if it has not been provided.
$params = $request->get_url_params();
if ( ! is_array( $params ) || empty( $params['id'] ) ) {
return $response;
}
$product_id = absint( $params['id'] );
// @todo we know the ID, so let's confirm it relates to a variable product before going any further.
// Make an internal request to load complete variation data.
$sub_request = new \WP_REST_Request( 'GET', "/wc/v3/products/{$product_id}/variations" );
$sub_response = rest_do_request( $sub_request );
if ( 200 === $sub_response->get_status() ) {
$full_variation_data = (array) $sub_response->get_data();
} else {
return $response;
}
// Add additional information to the response. In this case, we are overriding
// the existing `variations` property but it may be preferable to add this
// information as a new property, to avoid surprises for other API consumers.
$payload = $response->get_data();
$payload['variations'] = $full_variation_data;
$response->set_data( $payload );
return $response;
}, 10, 3 );
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment