Automattic\WooCommerce\Internal\RestApi\Routes\V4\ShippingZoneMethod
ShippingZoneMethodService::update_shipping_method_settings
Update settings of a shipping method.
Validates and saves shipping method settings. Settings vary by method type (e.g., flat_rate has 'cost', free_shipping has 'requires' and 'min_amount').
Method of the class: ShippingZoneMethodService{}
Hooks from the method
Returns
WC_Shipping_Method|\WP_Error. Updated method object on success, WP_Error on validation failure.
Usage
$ShippingZoneMethodService = new ShippingZoneMethodService(); $ShippingZoneMethodService->update_shipping_method_settings( $method, $settings );
- $method(WC_Shipping_Method) (required)
- Shipping method instance to update.
- $settings(array) (required)
- Settings to update as key-value pairs (e.g., ['title' => 'Express', 'cost' => '10']). Available settings depend on the specific shipping method type.
ShippingZoneMethodService::update_shipping_method_settings() ShippingZoneMethodService::update shipping method settings code WC 10.4.3
public function update_shipping_method_settings( $method, $settings ) {
if ( ! is_array( $settings ) ) {
return new \WP_Error(
'woocommerce_rest_shipping_method_invalid_settings',
__( 'Settings must be an array.', 'woocommerce' ),
array( 'status' => 400 )
);
}
$method->init_instance_settings();
$instance_settings = $method->instance_settings;
/**
* Transform setting keys to WooCommerce's expected format.
*
* WC_Settings_API::get_field_value() expects prefixed keys (e.g., 'woocommerce_flat_rate_1_title').
* Transform clean keys ('title') to prefixed keys before validation.
*/
$post_data = array();
foreach ( $settings as $key => $value ) {
$field_key = $method->get_field_key( $key );
$post_data[ $field_key ] = $value;
}
$form_fields = $method->get_instance_form_fields();
foreach ( $settings as $key => $value ) {
if ( isset( $form_fields[ $key ] ) ) {
try {
$instance_settings[ $key ] = $method->get_field_value( $key, $form_fields[ $key ], $post_data );
} catch ( \Exception $e ) {
return new \WP_Error(
'woocommerce_rest_shipping_method_invalid_setting',
$e->getMessage(),
array( 'status' => 400 )
);
}
}
}
/**
* Filter the instance settings values before saving.
*
* @since 9.4.0
* @param array $instance_settings Instance settings.
* @param WC_Shipping_Method $method Shipping method instance.
*/
$filtered_settings = apply_filters( 'woocommerce_shipping_' . $method->id . '_instance_settings_values', $instance_settings, $method );
$result = update_option( $method->get_instance_option_key(), $filtered_settings );
if ( $result ) {
$method->instance_settings = $instance_settings;
}
return $method;
}