Multiple checkbox doesn't work in wordpress settings api

I was creating a checkbox of roles n WordPress. I successfully generated them but the checked function doesn't seem to work.

Also, it is throwing this warning.

Warning: Illegal string offset 'ue_roles_confirm_Administrator' 

Here is the code I am using.

function username_editor_roles_callback() {
    global $wp_roles;
    $option = get_option( 'username_editor_settings' );
    $roles = $wp_roles-roles;

    foreach ($roles as $role) {
        $roleName = $role['name'];
        $output = sprintf('input type=checkbox name=username_editor_settings[ue_roles_confirm_%1$s] value=%1$s %2$slabel%1$s/labelbr', 
            $roleName,
            checked(1, $option[ue_roles_confirm_{$roleName}])
        );
        echo $output;
    }
}

I am unable to find why it doesn't work. I read all the questions regarding using an array with settings API but unfortunately, I didn't get what they are doing.

My main idea is to check which field is checked or not. For example, administrator and editor are checked.

Thanks in advance

NOTE: The values are successfully saved in the database inside the wp_options table. Update: I solved the checkbox part by using this method

Thanks to this question: Saving multiple checkboxes with WordPress settings api

function username_editor_roles_callback() {
    global $wp_roles;
    $roles = $wp_roles-roles;

    foreach ($roles as $role) {
        $roleName = $role['name'];
        $output = sprintf('input type=checkbox name=username_editor_settings[ue_roles_confirm][] value=%1$s %2$slabel%1$s/labelbr', 
            $roleName,
            checked( in_array($roleName, ue_settings_option()[ue_roles_confirm]), 1, false )
        );
        echo $output;
    }
}

But the warning issue still appears if I uncheck all the boxes.

Solved: I solved all the problems. Adding the working function in answer. If there is a better solution I will still accept the answer even the issue is fixed

Topic plugin-options settings-api options Wordpress

Category Web


Here is the function I used to solve the problem

function username_editor_roles_callback() {
    global $wp_roles;
    $roles = $wp_roles->roles;

    foreach ($roles as $role) {
        $roleName = $role['name'];
        $output = sprintf('<input type="checkbox" id="ue_roles_checkbox" name="username_editor_settings[ue_roles_confirm][]" value="%1$s" %2$s><label for="ue_roles_checkbox">%1$s</label><br>', 
            $roleName,
            checked( in_array($roleName, (array) ue_settings_option()["ue_roles_confirm"]), 1, false )
        );
        echo $output;
    }
}

About

Geeks Mental is a community that publishes articles and tutorials about Web, Android, Data Science, new techniques and Linux security.