Skip to content

Instantly share code, notes, and snippets.

@ipokkel
Last active November 8, 2023 07:38
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save ipokkel/9ea0a858661632d7f13c85b63299e846 to your computer and use it in GitHub Desktop.
Save ipokkel/9ea0a858661632d7f13c85b63299e846 to your computer and use it in GitHub Desktop.
<?php
/**
* This recipe assigns the readonly attribute to specific fields on the profile edit page.
*
* 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 read_only_profile_edit_fields_javascript() {
global $current_user;
// Add field names to be set as readonly to this array.
$read_only_field_names = array( 'first_name', 'last_name', 'display_name', 'user_email' );
// Bail if administrator or not logged in user.
if ( ! is_user_logged_in() || current_user_can( 'manage_options' ) ) {
return;
}
$reserved_field_names = array( 'user_email', 'display_name' );
// If read only field values that are not reserved field names are empty for user meta, drop the name from the array.
foreach ( $read_only_field_names as $key => $field_name ) {
if ( ! in_array( $field_name, $reserved_field_names ) && empty( get_user_meta( $current_user->ID, $field_name, true ) ) ) {
unset( $read_only_field_names[ $key ] );
}
}
// Bail if no read only fields.
if ( empty( $read_only_field_names ) ) {
return;
}
?>
<script>jQuery(document).ready(function ($) {
<?php
foreach ( $read_only_field_names as $field_name ) {
?>
$('#<?php echo esc_js( $field_name ); ?>').attr('readonly', true);
<?php
}
?>
});
</script>
<?php
}
function read_only_profile_edit_fields_init() {
// We're on the WP Dashboard but not an admin.
global $pagenow;
if ( is_admin() && 'profile.php' === $pagenow ) {
add_action( 'admin_footer', 'read_only_profile_edit_fields_javascript' );
}
}
add_action( 'init', 'read_only_profile_edit_fields_init' );
function read_only_profile_edit_fields_wp() {
// Bail if PMPro Core not active
if ( ! defined( 'PMPRO_VERSION' ) ) {
return false;
}
// We're on the front end profile edit page.
global $pmpro_pages;
if ( is_page( $pmpro_pages['member_profile_edit'] ) ) {
add_action( 'wp_footer', 'read_only_profile_edit_fields_javascript' );
}
}
add_action( 'wp', 'read_only_profile_edit_fields_wp' );
@ipokkel
Copy link
Author

ipokkel commented Nov 8, 2023

For toggling the readonly status for custom user fields only see https://gist.github.com/ipokkel/867fb8103f7e789ae089e55cbc93a9dc

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment