I have created 2 custom fields in ACF (Advanced Custom Fields) for posts. The first one is date and the another is volume. The volume field should be able to get data from the date field based on the year. But, nothing is getting updated.
Here is the code:
function UpdateVolumeField(){
$post_id = false;
$date_field = get_field('date_created', $post_id);
$volume_field = get_field('volume', $post_id);
//Calculation
$year = date_format(date_create($date_field), 'Y');
$vol = 0;
for($i=2010; $i<=$year ;$i++) {
$vol += 1;
}
update_field('volume' ,$vol, $post_id);
}
add_action('acf/save_post', 'UpdateVolumeField');
‘date_created’ is the field for date and ‘volume’ should be updated based on ‘date_created’ year.
When selecting a date in ‘date_created’ field and updating the post, the ‘volume’ field should be automatically updated, which can be seen when reloading the page. Here the ‘volume’ field will be starting from 2010 and hence forth. But nothing is getting updated.
What am I doing wrong (all plugins are updated to the latest versions)?
2
Answers
In your code, The post ID
$post_id
variable should be included as a function argument (dynamic variable) mandatory foracf/save_post'
hook, instead of including it statically inside your function withfalse
value, allowing to retrieve ‘date_created’ and ‘volume’ fields values from the post, and allowing to update ‘volume’ field value.Try the following revisited code instead:
It should better work now.
You must Including missing
$post_id
function argument variable