skip to Main Content

Evening everyone. I tried to look around the web to find a solution to this but couldn’t really find anything related. I just need to write a snippet that prevent users to change their display name by hiding the field in the "my account" page or any other smarter way possible. Thank you

2

Answers


  1. Thanks for your question. You can insert this code into your theme functions.php or use Code Snippets plugin. Hopefully, it will work.

    function wp_disable_display_name() {
        global $pagenow;
        if ( $pagenow == 'profile.php' ) {
        ?>
            <script>
                jQuery( document ).ready(function() {
                    jQuery('#display_name').prop('disabled', 'disabled');
                });
            </script>
        <?php
        }
    }
    add_action( 'admin_head', 'wp_disable_display_name', 15 );
    
    Login or Signup to reply.
  2. From your question I can assume that you are using WooCommerce. You need to make a couple of things done to achieve it:

    1. Remove account_display_name field from My Account template file:

    Firstly, duplicate form-edit-account.php file

    /wp-content/plugins/woocommerce/templates/myaccount/form-edit-account.php

    to your child theme folder

    /wp-content/themes/your_child_theme/woocommerce/myaccount/form-edit-account.php

    Then open copied file and remove html markup and php code related to account_display_name field:

        <p class="woocommerce-form-row woocommerce-form-row--wide form-row form-row-wide">
        <label for="account_display_name"><?php esc_html_e( 'Display name', 'woocommerce' ); ?>&nbsp;<span class="required">*</span></label>
        <input type="text" class="woocommerce-Input woocommerce-Input--text input-text" name="account_display_name" id="account_display_name" value="<?php echo esc_attr( $user->display_name ); ?>" />
        <span><em><?php esc_html_e( 'This will be how your name will be displayed in the account section and in reviews', 'woocommerce' ); ?></em></span>
        </p>
        <div class="clear"></div>
    
    1. Use woocommerce_save_account_details_required_fields hook to unset account_display_name field from the required fields. This is necessary to avoid validation error when saving changes on My Account page.

    Place following php code into your child’s theme functions.php file:

        add_filter('woocommerce_save_account_details_required_fields', 'remove_required_fields'); 
        function remove_required_fields( $required_fields ) {
            unset($required_fields['account_display_name']);
            return $required_fields;
        }
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search