Skip to content

Instantly share code, notes, and snippets.

@BhargavBhandari90
Created November 28, 2021 07:48
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save BhargavBhandari90/8f4de1312525bf389919c1a0c010e32e to your computer and use it in GitHub Desktop.
Save BhargavBhandari90/8f4de1312525bf389919c1a0c010e32e to your computer and use it in GitHub Desktop.
Dynamic options for ACF field
<?php
/**
* Set user roles as an option.
*
* @param array $field
* @return array
*/
function load_roles( $field ) {
// Added this because it was giving fatal error.
require_once ABSPATH . '/wp-admin/includes/user.php';
// Get roles as per backend.
$editable_roles = array_reverse( get_editable_roles() );
// Don't show administrator. Administrator should have all the access.
if ( ! empty( $editable_roles ) && isset( $editable_roles['administrator'] ) ) {
unset( $editable_roles['administrator'] );
}
// Bail, if anything goes wrong.
if ( empty( $editable_roles ) ) {
return $field;
}
foreach ( $editable_roles as $role => $details ) {
$name = translate_user_role( $details['name'] );
$field['choices'][ esc_attr( $role ) ] = esc_html( $name );
}
return $field;
}
add_filter( 'acf/load_field/name=role', 'load_roles' );
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment