Ad

How Do I Update_post_meta With A Checkbox Array?

How do I take all the checked options and fill my Custom Post Type Checkbox field?

Here is the form:

    <form action="#" method="post">
          <div class="row">
          <div class="column left labels">
<input type="checkbox" name="grips[]" value="Top (T1)"><label>Top (T1)</label>
<input type="checkbox" name="grips[]" value="High (12)"><label>High (12)</label>
                </div>
              <div class="column left labels">
<input type="checkbox" name="grips[]" value="Mid (23)"><label>Mid (23)</label>
<input type="checkbox" name="grips[]" value="Low (34)"><label>Low (34)</label>
              </div>
              <div class="column left labels">
<input type="checkbox" name="grips[]" value="Bottom (P4)"><label>Bottom (P4)</label>
<input type="checkbox" name="grips[]" value="Other"><label>Other</label>
    </div>
    </div>

<input type="submit" name="submit" value="Submit"/>
</form>

I want to do this, but this doesn't work, it will only take the last value in the array:

__update_post_meta( $the_post_id, 'grips', $_POST['grips']);

I tried to loop through, but that will remove all the other checkmarks and leave only the last one added as well:

foreach($_POST['grips'] as $selected){
    echo $selected."</br>";
__update_post_meta( $the_post_id, 'grips', $selected);  
}

This is what I have in my Functions.php file: I imagine I need another function for arrays since this one only updates single custom fields:

function __update_post_meta( $post_id, $field_name, $value = '' ) {
    if ( empty( $value ) OR ! $value )
    {
        delete_post_meta( $post_id, $field_name );
    }
    elseif ( ! get_post_meta( $post_id, $field_name ) )
    {
        add_post_meta( $post_id, $field_name, $value );
    }
    else
    {
        update_post_meta( $post_id, $field_name, $value );
    }
}

Here is a picture of the Custom field I have set: enter image description here

Ad

Answer

I still want to learn how to do this with Meta data. But if you have ACF, the easy way to do this is via:

$field_key = "grips";
$value = $_POST['grips']; 
update_field( $field_key, $value, $the_post_id );
}
Ad
source: stackoverflow.com
Ad