dongou0524 2019-03-14 16:59
浏览 57
已采纳

使用自定义Wordpress API端点更新WooCommerce产品

I am trying to update my WooCommerce products with an API call to a custom Wordpress Endpoint. I am successfully getting my call received and the data is accessible, but the product is not actually updating.

My endpoint:

add_action('rest_api_init', function(){
  register_rest_route('productupdate/v1', '/update', array(
      'methods' => 'POST',
      'callback' => 'determine_request'
  ));
});

So I make my POST request to: https://example.com/wp-json/productupdate/v1/update

In my determine_request function, I have a number of places that I write to a log file to ensure that helper functions are being called and data is received and readable, and the log reflects that these are all working as intended. The only problem is that the products are never actually updated.

Example of what I'm doing (this is simplified to get a basic idea of how I'm handling this):

function determine_request($request){
  $data = $request -> get_json_params()['Inserted'][0];
  $sku = $data['InventoryID'];
  $product_id = wc_get_product_id_by_sku($sku);
  $product = wc_get_product($product_id);
  $current_name = $product->get_name();
  $sent_name = $data['Description'];
  if($current_name != $sent_name){
    write_to_log("Current Name does not match sent Name!");
    write_to_log("Changing name from: " . $current_name);
    write_to_log('Changing name to: ' . $sent_name);
    $product->set_name($sent_name);
  } else {
    write_to_log("Current Name matches sent Name. Skipping...");
  }
 }

When I do this, my log shows me all the right things, but no update occurs. I tried adding a $product->save(); to the end of the function, but that didn't solve it. I tried adding Basic Auth with an administrator login and password in my postman request, but this also did not do anything.

What am I missing or doing wrong to get the product to update?

  • 写回答

2条回答 默认 最新

  • dongxu4023 2019-03-14 18:13
    关注

    So what actually ended up working for me was this.

    I didn't need Basic Auth (turned it off after I got it working to confirm). But I DID need to do a $product->save(); in every helper method after setting a field. for example:

    function main(){
      $product_id = 12345;
      $product = wc_get_product($product_id);
      helper1($product);
      helper2($product);
    }
    
    function helper1($product){
      $product->set_name("foo");
      $product->save();
    }
    
    function helper2($product){
      $product->set_short_description("here is a short description");
      $product->save();
    }
    

    Hopefully this helps someone else in the future if they get stuck like I did.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?