woocommerce / woocommerce-rest-api

This is the WooCommerce core REST API Package. It runs standalone as a feature plugin too.
71 stars 46 forks source link

How to set the default variation for the product using the api #279

Open abdullahTreesal opened 1 year ago

abdullahTreesal commented 1 year ago

I'm unable to set the default attribute using the API please help

amirshnll commented 2 months ago

Hi @abdullahTreesal , If you're having trouble setting the default attribute using the WooCommerce REST API, try these steps:

Use the Right Endpoint and Method: Update the product using the PUT method on the products/{product_id} endpoint.

Format Default Attributes Correctly: Your default_attributes should look like this:

{
  "default_attributes": [
    { "id": 1, "option": "Blue" },
    { "id": 2, "option": "Large" }
  ]
}

Fetch Variation Attributes: First, get the variation details with GET /products/{product_id}/variations/{variation_id}. Use these details to format the default_attributes for your update request.

Sample PHP code:

$variation_data = $this->client->get($product_url . '/variations/' . strval($variation_id) . $query_authentication_data);
$variation_data = json_decode($variation_data->getBody(), true);
$variation_attributes = $variation_data['attributes'] ?? [];
$update_data = [
   'default_attributes' => $variation_attributes
];

$this->client->put($product_url, [
   'json' => $update_data,
   'headers' => [
      'Content-Type' => 'application/json'
    ]
]);

Hope this helps!