Hi, I’m showing the checkbox selected by the user from the frontend and everything works fine when I have at least one checkbox selected, but the problem happens when there is no checkbox selected, the code I have is:
$options = get_field('preferences', 'user_'.$current_user->ID);
$field = get_field_object('preferences','user_'.$current_user->ID);
?>
<input type="hidden" value="<?php echo 'acf['.$field['key'].']' ?>"/>
<?php
if( $field ){
foreach ( $field['choices'] as $key => $value) {
if ( is_array($options && in_array( $key, $options ) ) {
$checked = 'checked';
}else{
$checked = '';
}
echo '<p class="field"><input type="checkbox" '.$checked.' name="acf['.$field['key'].'][]" id="preferences" value="'.$key.'">'.$value.'</p>';
}
}
?>
can you help me please. Thank you
Do you mean that, if the field has never been set for the user. In other words, the user was never edited to select any checkboxes rather than the user was edited and all boxes unchecked.
In this case ACF cannot find the field object because there is not association found between the field and the user. Try using the field key.
Instead of
$field = get_field_object('preferences','user_'.$current_user->ID);
try
$field = get_field_object('field_1245678'); // or whatever your field key is
Thank you, it’s works! =)