Created
November 8, 2023 07:28
-
-
Save ipokkel/867fb8103f7e789ae089e55cbc93a9dc to your computer and use it in GitHub Desktop.
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 | |
/** | |
* Toggle user field readonly based on user meta value or user capabilities. | |
* This should allow members to fill in a field at checkout but set to readonly | |
* on their profile edit page if they are not an admin or do not have a value. | |
* | |
* This assumes a field's readonly property is set to true. | |
* | |
* 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_toggle_user_field_readonly() { | |
global $pmpro_user_fields, $current_user; | |
$readonly_fields = array( 'example_text' ); | |
// Don't break if PMPro is out of date or not loaded. | |
if ( ! function_exists( 'pmpro_add_user_field' ) || empty( $pmpro_user_fields ) ) { | |
return; | |
} | |
foreach ( $pmpro_user_fields as $field_group => $fields ) { | |
foreach ( $fields as $field ) { | |
if ( in_array( $field->name, $readonly_fields ) ) { | |
// skip field if readonly is already false. | |
if ( ! $field->readonly ) { | |
continue; | |
} | |
// Remove readonly if user does not have a value for the field or is an admin. | |
if ( ! is_user_logged_in() || empty( get_user_meta( $current_user->ID, $field->meta_key, true ) ) || current_user_can( 'manage_options' ) || current_user_can( 'pmpro_membership_manager' ) ) { | |
$field->readonly = false; | |
} | |
} | |
} | |
} | |
} | |
add_action( 'init', 'my_pmpro_toggle_user_field_readonly' ); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
For setting default user fields, e.g. email address, to readonly see https://gist.github.com/ipokkel/9ea0a858661632d7f13c85b63299e846