Set Woocommerce Product Price Before Saving with Custom Calculation
Ini adalah contoh menyimpan harga berdasarkan hasil perhitungan
add_action('woocommerce_before_product_object_save', 'set_custom_price_on_save');
public function set_custom_price_on_save($product)
{
$base_price = $product->get_meta('_syncplugin_base_price');
$profit_percent = SyncPluginUtil::get_pricing_profit_percent($base_price);
$profit_amount = ($profit_percent / 100) * $base_price;
$manual_price = $product->get_meta('_syncplugin_manual_update_price', true);
$manual_price = $manual_price === 'yes' ? 'yes' : 'no';
// Get the category IDs
$category_ids = $product->get_category_ids();
//get tax cost
$cost_percent = SyncPluginUtil::get_cost_from_term($category_ids);
$cost_amount = ($cost_percent / 100) * $base_price;
//get transport cost amount
$transport_amount = SyncPluginUtil::get_transport_from_term($category_ids);
$sellingprice = round($base_price + $profit_amount + $cost_amount + $transport_amount, 2);
$integerPart = floor($sellingprice);
$decimalPart = $sellingprice - $integerPart;
//SyncPluginUtil::set_log("sku: $sku, Selling price before round: $sellingprice", 'synplugin-api');
if ($decimalPart < 0.5) {
// Decimal is less than 0.5: Reduce integer part by 1 and set decimal to .9
$sellingprice = ($integerPart - 1) + 0.9;
} else {
// Decimal is 0.5 or more: Keep integer part and set decimal to .9
$sellingprice = $integerPart + 0.9;
}
$product->update_meta_data('_syncplugin_cost_percent', $cost_percent);
$product->update_meta_data('_syncplugin_cost_amount', $cost_amount);
$product->update_meta_data('_syncplugin_transport_amount', $transport_amount);
$product->update_meta_data('_syncplugin_profit_percent', $profit_percent);
$product->update_meta_data('_syncplugin_profit_amount', $profit_amount);
SyncPluginUtil::set_log("Update price when saving.", 'synplugin-api');
if ($manual_price == 'no') {
SyncPluginUtil::set_log("Automatic price update", 'synplugin-api');
$product->set_regular_price($sellingprice);
// Be sure to use the correct decimal price.
} else {
SyncPluginUtil::set_log("Manual price update", 'synplugin-api');
}
SyncPluginUtil::set_log(str_repeat('-', 200), 'synplugin-api');
//SyncPluginUtil::set_log("saving product for id: $product_id", 'synplugin-api');
}