Revy
Revy

Reputation: 31

remove product from category using rest-api

I need to remove a lot of product from a category in my store

i tried to use update product and editing the category properties in the product, this one

PUT /wp-json/wc/v3/products/

this is the script i used

for ($i=0; $i < 22; $i++) {
  $products = $woocommerce->get('products?category='.$categoryToRemove.'&per_page=50&page=1');

  $update_data = array();

  foreach ($products as $key1 => $product) {
    if(count($product->categories)>1){
      foreach ($product->categories as $key2 => $category) {
          if($category->id == $categoryToRemove){
          unset($product->categories[$key2]);
        }
      }
    }
    $woocommerce->put('products/'.$product->id, ['categories' => $product->categories]);
  }

}

the product property doesn't changed when i checked it and the product still show inside the cateogories in the store and when i'm call all products via api by filtering the category.

Upvotes: 1

Views: 1847

Answers (1)

Someguy
Someguy

Reputation: 414

There are a few way's you could go about this.

Let's start with what you've been doing already trying to Update the Products.

My Advice is updating individual products, Either one at a time or Batches

You can find the Official doc on this here Link

So we'll want to update "status": "publish", To something like "status" : "draft"

We do this with [PUT] /wp-json/wc/v3/products/<id> E.G

curl -X POST https://example.com/wp-json/wc/v3/products/batch \
    -u consumer_key:consumer_secret \
    -H "Content-Type: application/json" \
    -d '{ "update": [
    {
      "id": 799,
      "default_attributes": [
        {
          "id": 6,
          "status": "draft",
          "name": "Color",
          "option": "Green"
        },
        {
          "id": 0,
          "status": "draft",
          "name": "Size",
          "option": "M"
        }
      ]
    }
  ],

Now We can also approach this by "Deleting" a product either permanently or moving it to the Trash

We do this one of 2 ways

This will move the product to trash

    -u consumer_key:consumer_secret```

This will Permanently delete the Product
curl -X DELETE https://example.com/wp-json/wc/v3/products/794?force=true \
    -u consumer_key:consumer_secret

So in your case, You're using "Put" to try and Remove a product, So your telling the API Hey Update this product and giving it nothing to update so It just Refreshes the Product. Now you mention you remove the Product on Click So I can see you retrieve the Individual Products ID, So if we want to Delete it simply

$woocommerce->DELETE('products/'.$product->id,'?force=false');

Upvotes: 1

Related Questions