Agregar campos a la pantalla "Agregar nuevo usuario" en el tablero

11

Me gustaría agregar el campo "Nombre de la compañía" a la página de agregar nuevo usuario en el panel de administración. He hecho un poco de búsqueda y no he podido encontrar detalles sobre cómo hacer esto. Puedo agregar fácilmente información a la página de perfil y registrarme con ...

   function my_custom_userfields( $contactmethods ) {
    //Adds customer contact details
    $contactmethods['company_name'] = 'Company Name';
    return $contactmethods;
   }
   add_filter('user_contactmethods','my_custom_userfields',10,1);

Pero no hay dados en otra cosa.

    
pregunta Zach Shallbetter 23.07.2011 - 00:22

9 respuestas

-1

Para hacer esto, tendrá que cambiar manualmente la página user-new.php. No es la forma correcta de manejarlo, pero si estás desesperadamente necesitado, así es como se hace.

Agregué

<tr class="form-field">
    <th scope="row"><label for="company_name"><?php _e('Company Name') ?> </label></th>
    <td><input name="company_name" type="text" id="company_name" value="<?php echo esc_attr($new_user_companyname); ?>" /></td>
</tr>

También agregué la información a functions.php

   function my_custom_userfields( $contactmethods ) {
    $contactmethods['company_name']             = 'Company Name';
    return $contactmethods;
   }
   add_filter('user_contactmethods','my_custom_userfields',10,1);
    
respondido por el Zach Shallbetter 03.08.2011 - 20:01
16

user_new_form es el gancho que puede hacer la magia aquí.

function custom_user_profile_fields($user){
  ?>
    <h3>Extra profile information</h3>
    <table class="form-table">
        <tr>
            <th><label for="company">Company Name</label></th>
            <td>
                <input type="text" class="regular-text" name="company" value="<?php echo esc_attr( get_the_author_meta( 'company', $user->ID ) ); ?>" id="company" /><br />
                <span class="description">Where are you?</span>
            </td>
        </tr>
    </table>
  <?php
}
add_action( 'show_user_profile', 'custom_user_profile_fields' );
add_action( 'edit_user_profile', 'custom_user_profile_fields' );
add_action( "user_new_form", "custom_user_profile_fields" );

function save_custom_user_profile_fields($user_id){
    # again do this only if you can
    if(!current_user_can('manage_options'))
        return false;

    # save my custom field
    update_usermeta($user_id, 'company', $_POST['company']);
}
add_action('user_register', 'save_custom_user_profile_fields');
add_action('profile_update', 'save_custom_user_profile_fields');

Para obtener más información, visite mi blog: enlace

    
respondido por el Tahir Yasin 12.11.2014 - 15:08
13

Tuve la misma necesidad y creé el siguiente hack:

<?php
function hack_add_custom_user_profile_fields(){
    global $pagenow;

    # do this only in page user-new.php
    if($pagenow !== 'user-new.php')
        return;

    # do this only if you can
    if(!current_user_can('manage_options'))
        return false;

?>
<table id="table_my_custom_field" style="display:none;">
<!-- My Custom Code { -->
    <tr>
        <th><label for="my_custom_field">My Custom Field</label></th>
        <td><input type="text" name="my_custom_field" id="my_custom_field" /></td>
    </tr>
<!-- } -->
</table>
<script>
jQuery(function($){
    //Move my HTML code below user's role
    $('#table_my_custom_field tr').insertAfter($('#role').parentsUntil('tr').parent());
});
</script>
<?php
}
add_action('admin_footer_text', 'hack_add_custom_user_profile_fields');


function save_custom_user_profile_fields($user_id){
    # again do this only if you can
    if(!current_user_can('manage_options'))
        return false;

    # save my custom field
    update_usermeta($user_id, 'my_custom_field', $_POST['my_custom_field']);
}
add_action('user_register', 'save_custom_user_profile_fields');
    
respondido por el NkR 09.01.2013 - 20:57
3

Necesitas hacer 2 cosas.

  1. campos de registro
  2. Guardar campos

Nota: El siguiente ejemplo solo funciona para administrator rol de usuario.

1. Registrar campos

Para Agregar nuevo usuario use la acción user_new_form

Para Perfil de usuario use las acciones show_user_profile , edit_user_profile

Registro de campos Fragmento:

/**
 * Add fields to user profile screen, add new user screen
 */
if( !function_exists('m_register_profile_fields') ) {

    //  This action for 'Add New User' screen
    add_action( 'user_new_form', 'm_register_profile_fields' );

    //  This actions for 'User Profile' screen
    add_action( 'show_user_profile', 'm_register_profile_fields' );
    add_action( 'edit_user_profile', 'm_register_profile_fields' );

    function m_register_profile_fields( $user ) {

        if ( !current_user_can( 'administrator', $user_id ) )
            return false;

        ?>

        <h3>Client Portal</h3>
        <table class="form-table">
            <tr>
                <th><label for="dropdown">Portal Category</label></th>
                <td>
                    <input type="text" class="regular-text" name="portal_cat" value="<?php echo esc_attr( get_the_author_meta( 'portal_cat', $user->ID ) ); ?>" id="portal_cat" /><br />
                </td>
            </tr>
        </table>
    <?php }
}

2. Guardar campos

Para Agregar nuevo usuario use la acción user_register

Para Perfil de usuario use las acciones personal_options_update , edit_user_profile_update

Guardar campos Fragmento:

/**
 *  Save portal category field to user profile page, add new profile page etc
 */
if( !function_exists('m_register_profile_fields') ) {

    //  This action for 'Add New User' screen
    add_action( 'user_register', 'cp_save_profile_fields' );

    //  This actions for 'User Profile' screen
    add_action( 'personal_options_update', 'cp_save_profile_fields' );
    add_action( 'edit_user_profile_update', 'cp_save_profile_fields' );

    function cp_save_profile_fields( $user_id ) {

        if ( !current_user_can( 'administrator', $user_id ) )
            return false;

        update_usermeta( $user_id, 'portal_cat', $_POST['portal_cat'] );
    }
}

Fragmento de código completo:

/**
 * Add fields to user profile screen, add new user screen
 */
if( !function_exists('m_register_profile_fields') ) {

    //  This action for 'Add New User' screen
    add_action( 'user_new_form', 'm_register_profile_fields' );

    //  This actions for 'User Profile' screen
    add_action( 'show_user_profile', 'm_register_profile_fields' );
    add_action( 'edit_user_profile', 'm_register_profile_fields' );

    function m_register_profile_fields( $user ) {

        if ( !current_user_can( 'administrator', $user_id ) )
            return false;

        ?>

        <h3>Client Portal</h3>
        <table class="form-table">
            <tr>
                <th><label for="dropdown">Portal Category</label></th>
                <td>
                    <input type="text" class="regular-text" name="portal_cat" value="<?php echo esc_attr( get_the_author_meta( 'portal_cat', $user->ID ) ); ?>" id="portal_cat" /><br />
                </td>
            </tr>
        </table>
    <?php }
}


/**
 *  Save portal category field to user profile page, add new profile page etc
 */
if( !function_exists('m_register_profile_fields') ) {

    //  This action for 'Add New User' screen
    add_action( 'user_register', 'cp_save_profile_fields' );

    //  This actions for 'User Profile' screen
    add_action( 'personal_options_update', 'cp_save_profile_fields' );
    add_action( 'edit_user_profile_update', 'cp_save_profile_fields' );

    function cp_save_profile_fields( $user_id ) {

        if ( !current_user_can( 'administrator', $user_id ) )
            return false;

        update_usermeta( $user_id, 'portal_cat', $_POST['portal_cat'] );
    }
}
    
respondido por el maheshwaghmare 22.08.2016 - 13:47
2

La solución alternativa I está disponible mediante el uso de user_new_form_tag que reside dentro de la etiqueta inicial de formulario de la página user-new.php . Está al final, por lo que si imprime HTML después de eso, solo necesita comenzar la salida con > y eliminar el último > de su propio código. Como en:

function add_new_field_to_useradd()
{
    echo "><div>"; // Note the first '>' here. We wrap our own output to a 'div' element.

    // Your wanted output code should be here here.

    echo "</div"; // Note the missing '>' here.
}

add_action( "user_new_form_tag", "add_new_field_to_useradd" );

El user_new_form_tag está situado en user-new.php alrededor de la línea 303 (al menos en WP3.5.1):

...
<p><?php _e('Create a brand new user and add it to this site.'); ?></p>
<form action="" method="post" name="createuser" id="createuser" class="validate"<?php do_action('user_new_form_tag');?>>
<input name="action" type="hidden" value="createuser" />
...

Por supuesto, el inconveniente aquí es que todos los campos personalizados deben aparecer primero en el formulario, antes de los campos declarados en el núcleo de WP.

    
respondido por el ojrask 19.06.2013 - 14:22
1

user_contactmethods filter hook no se llama en la página user-new.php por lo que no funcionará y lamentablemente si tomas un busque en la fuente verá que no hay ningún gancho que se pueda usar para agregar campos adicionales al formulario para agregar nuevo usuario.

Por lo tanto, esto solo puede hacerse modificando los archivos principales (BIG NO NO) o agregando los campos mediante JavaScript o jQuery y capturando los campos.

o puede crear un Boleto en el Trac

    
respondido por el Bainternet 23.07.2011 - 11:32
1

El siguiente código mostrará "Información biográfica" en el formulario "Agregar usuario"


function display_bio_field() {
  echo "The field html";
}
add_action('user_new_form', 'display_bio_field');

    
respondido por el Linish 06.02.2014 - 09:31
1

Los ganchos son importantes, no importa cómo ordenamos los campos de formulario dentro de la función. Siga mis comentarios en línea. A partir de WordPress 4.2.2 tenemos muchos ganchos ahora:

<?php
/**
 * Declaring the form fields
 */
function show_my_fields( $user ) {
   $fetched_field = get_user_meta( $user->ID, 'my_field', true ); ?>
    <tr class="form-field">
       <th scope="row"><label for="my-field"><?php _e('Field Name') ?> </label></th>
       <td><input name="my_field" type="text" id="my-field" value="<?php echo esc_attr($fetched_field); ?>" /></td>
    </tr>
<?php
}
add_action( 'show_user_profile', 'show_my_fields' ); //show in my profile.php page
add_action( 'edit_user_profile', 'show_my_fields' ); //show in my profile.php page

//add_action( 'user_new_form_tag', 'show_my_fields' ); //to add the fields before the user-new.php form
add_action( 'user_new_form', 'show_my_fields' ); //to add the fields after the user-new.php form

/**
 * Saving my form fields
 */
function save_my_form_fields( $user_id ) {
    update_user_meta( $user_id, 'my_field', $_POST['my_field'] );
}
add_action( 'personal_options_update', 'save_my_form_fields' ); //for profile page update
add_action( 'edit_user_profile_update', 'save_my_form_fields' ); //for profile page update

add_action( 'user_register', 'save_my_form_fields' ); //for user-new.php page new user addition
    
respondido por el Mayeenul Islam 17.06.2015 - 14:02
0

Esto no lo hará para agregar una nueva página de usuario, pero si desea que suceda en la página "Su perfil" (donde los usuarios pueden editar su perfil), puede intentar esto en functions.php:

add_action( 'show_user_profile', 'my_show_extra_profile_fields' );
add_action( 'edit_user_profile', 'my_show_extra_profile_fields' );
function my_show_extra_profile_fields( $user ) { ?>
    <h3>Extra profile information</h3>
    <table class="form-table">
        <tr>
            <th><label for="companyname">Company Name</label></th>
            <td>
                <input type="text" name="companyname" id="companyname" value="<?php echo esc_attr( get_the_author_meta( 'companyname', $user->ID ) ); ?>" class="regular-text" /><br />
                <span class="description">Where are you?</span>
            </td>
        </tr>
    </table>
<?php }
    
respondido por el AndrettiMilas 09.01.2013 - 22:50

Lea otras preguntas en las etiquetas