Last active
May 12, 2023 13:44
-
-
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.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?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