Home › Forums › General Issues › Total Number of Checkboxes Checked
Hi, I thought figured this out but I guess I jumped the gun. I am trying to auto calculate the a number field by the total amount of checkboxes that are checked. I have multiple custom fields that I am doing this with.
The top one works perfectly but when I add the second one and so on, it gives me an error.
count(): Argument #1 ($value) must be of type Countable|array
add_action('acf/save_post','calc_titles');
$post_id = 'teams';
function calc_titles($post_id) {
//First Part that works
$value = count(get_field('16th_region_title_year_won'));
$sixteen = "total_16th_region_titles";
update_field($sixteen,$value,$post_id);
//Second Part
$value = count(get_field('3rd_region_title_year_won'));
$third = "total_3rd_region_titles";
update_field($third,$value,$post_id);
}
Thanks!
Went a different route.
// Hook to save_post action
add_action('save_post', 'update_number_field');
function update_number_field($post_id) {
// Check if it's an autosave
if (defined('DOING_AUTOSAVE') && DOING_AUTOSAVE) {
return;
}
// Check if the user has permission to edit the post
if (!current_user_can('edit_post', $post_id)) {
return;
}
// Check if the post type is the one you want to target (e.g., 'post' or 'page')
$post_type = get_post_type($post_id);
if ($post_type != 'team') {
return;
}
// Get the values of the checkbox field
$checkbox_values = get_post_meta($post_id, 'state_title_years_won', true);
// Calculate the number of checked checkboxes
$number_field_value = is_array($checkbox_values) ? count($checkbox_values) : 0;
// Update the number field
update_post_meta($post_id, 'total_state_championships_won', $number_field_value);
}
I must have missed you OP.
The reason it is failing is that you are probably calling get_field() for a field without a value, as you have seen your updated code, you must check that the field is actually an array before you try to count it.
You must be logged in to reply to this topic.
Welcome to the Advanced Custom Fields community forum.
Browse through ideas, snippets of code, questions and answers between fellow ACF users
Helping others is a great way to earn karma, gain badges and help ACF development!
We use cookies to offer you a better browsing experience, analyze site traffic and personalize content. Read about how we use cookies and how you can control them in our Privacy Policy. If you continue to use this site, you consent to our use of cookies.