0

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$s><label>%1$s</label><br>', 
            $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$s><label>%1$s</label><br>', 
            $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

1 Answer 1

0

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;
    }
}

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.