I have a requirement where the number of checkboxes outputted in the metabox is not fixed. Had it been fixed, I could’ve followed any one of the tutorials on the internet which suggests I name each checkbox and save it using update_post_meta()
In my case, I have named the checkbox in array notation as name="multval[]"
since the number of checkboxes is unknown.
I’m failing to understand how to use:
get_post_meta()
checked()
update_post_meta()
when it comes to accessing checkboxes when it is named as an array.
The Code:
<?php
add_action( 'add_meta_boxes', function() {
add_meta_box( 'custom-metabox', 'Select values', 'fill_metabox', 'post', 'normal' );
});
function fill_metabox( $post ) {
wp_nonce_field( basename(__FILE__), 'mam_nonce' );
// How to use 'get_post_meta()' for multiple checkboxes as array?
$elements = get_elements(); //returns an associative array
foreach ( $elements as $element) {
?>
<p>
<input
type = "checkbox"
name = "multval[]"
value = <?php echo $element;?>
//How to use checked() function in case of
//multiple checkbox as arrays
>
<?php echo $element;?>
</p>
<?php
}
}
add_action( 'save_post', function( $post_id ) {
$is_autosave = wp_is_post_autosave( $post_id );
$is_revision = wp_is_post_revision( $post_id );
$is_valid_nonce = ( isset( $_POST[ 'mam_nonce' ] ) && wp_verify_nonce( $_POST[ 'mam_nonce' ], basename( __FILE__ ) ) ) ? 'true' : 'false';
if ( $is_autosave || $is_revision || !$is_valid_nonce ) {
return;
}
/*How to run a loop to save values for each checkbox?*/
});