Created
November 28, 2021 07:48
-
-
Save BhargavBhandari90/8f4de1312525bf389919c1a0c010e32e to your computer and use it in GitHub Desktop.
Dynamic options for ACF field
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?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