Support

Account

Home Forums General Issues Total Number of Checkboxes Checked

Solving

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.

Viewing 3 posts - 1 through 3 (of 3 total)

You must be logged in to reply to this topic.