Forked from ipokkel/lock-down-first-and-last-name.php
Last active
August 18, 2025 16:22
-
-
Save kimwhite/90c1e10eb489ab69238753d47d4b44c6 to your computer and use it in GitHub Desktop.
Make custom User Fields read-only for registered members #pmpro
This file contains hidden or 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 | |
| /** | |
| * Change PMPro User Field type based on user role. | |
| * | |
| * This code allows admin users to edit fields that appear as readonly for other users. | |
| * | |
| * title: Change PMPro User Field Type by Role | |
| * collection: user-fields | |
| * category: custom-fields | |
| * | |
| * customize with your user fields "name" see lines 31, or add others. | |
| * | |
| * You can add this recipe to your site by creating a custom plugin | |
| * or using the Code Snippets plugin available for free in the WordPress repository. | |
| * Read this companion article for step-by-step directions on either method: | |
| * https://www.paidmembershipspro.com/create-a-plugin-for-pmpro-customizations/ | |
| */ | |
| function my_pmpro_dynamic_user_fields_by_role() { | |
| // Don't break if PMPro isn't fully loaded. | |
| if ( ! function_exists( 'pmpro_add_user_field' ) ) { | |
| return; | |
| } | |
| // Determine field type: readonly by default, editable for admins. | |
| $field_type = 'readonly'; | |
| if ( is_user_logged_in() && current_user_can( 'manage_options' ) ) { | |
| $field_type = 'text'; | |
| } | |
| // Define your custom fields here: key = meta key, label = field label. | |
| $custom_fields = array( | |
| 'company' => 'Company', | |
| 'mm_location' => 'Location', | |
| ); | |
| // Add a custom group for organization. | |
| pmpro_add_field_group( 'Membership Information' ); | |
| // Loop through the fields and register them with the appropriate type. | |
| foreach ( $custom_fields as $meta_key => $label ) { | |
| $field = new PMPro_Field( | |
| $meta_key, | |
| $field_type, | |
| array( | |
| 'label' => $label, | |
| 'profile' => "only", | |
| ) | |
| ); | |
| pmpro_add_user_field( 'Membership Information', $field ); | |
| } | |
| } | |
| add_action( 'init', 'my_pmpro_dynamic_user_fields_by_role' ); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment