Products
GG网络技术分享 2025-03-18 16:12 2
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?
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.
###
function set_name()
will not update anything in the database itself and should only change what is stored in the class object.
Try this instead
$product_detils = array(\'ID\' => $product_id,
\'post_title\' => $sent_name,
);
wp_update_post($product_detils);
Demand feedback