Calculate a Listing attribute value based on other attributes

I want to calculate the yield for real estate ads listings , I can get the values from the listing to make the calculation, but the listing is not updated when I call the save function.
Any idea why ?

// Calcul du rendement brut loyer/prix de vente
add_action(	'hivepress/v1/models/listing/update', 'update_rendement',10,2);

	function update_rendement ( $listing_id, $listing ) {
		
		// To avoid a callback
		remove_action('hivepress/v1/models/listing/update', 'update_rendement', 10, 2);
		
		// Get loyer and selling price
		$loyer = $listing->get_loyer();
		$prix = $listing->get_prix();
		
		// Calculate rendement
		if ($prix!=0) $rendement = 100*$loyer / $prix; else $rendement=0;
		$message = "Calcul effectué ".$rendement." pour $loyer $prix";
		error_log($message,0);
		
		// Check and set
		if ( $listing->get_rendement() !== $rendement ) {
			error_log("Boucle de mise a jour 1",0);
			$listing->set_rendement( $rendement )->save_rendement();
		}
	}

Sorry for the delay.

The snippet seems to be ok, please try debugging it with error_log and var_dump to check where it fails. Maybe the set/save line doesn’t run at all, or the supplied value is in the wrong format (you can check this via $listing->_get_errors() after saving).

Another approach is using the hivepress/v1/models/listing/errors filter hook, it runs just before the update so you can get the attribute values and set the value for another one before the update to prevent duplicate database queries.

Hope this helps

Thank you for your reply. In fact , it seems to work when someone submit a listing but not when I try to make a change through the wordpress back office, so the hivepress/v1/models/listing/update is probably not called when an update is done through the back office.

This topic was automatically closed 30 days after the last reply. New replies are no longer allowed.