首页 问答 正文

如何在WordPress中实现网站的会员注册和会员管理?

注册会员 / 悠然自学 / 2023-07-11/ 浏览 137 次

在WordPress中实现网站的会员注册和会员管理可以通过以下步骤完成:

  1. 创建会员注册页面:

    • 在WordPress后台导航栏中选择“页面” > “添加新页面”;
    • 输入页面标题为“会员注册”;
    • 在页面编辑器中插入会员注册表单,如下示例代码:
      <form method="post" action="<?php echo esc_url( admin_url('admin-post.php') ); ?>">
       <input type="hidden" name="action" value="user_registration">
       <label for="username">用户名:</label>
       <input type="text" name="username" id="username" required>
       <label for="password">密码:</label>
       <input type="password" name="password" id="password" required>
       <input type="submit" value="注册">
      </form> 
    • 点击“发布”按钮保存页面。
  2. 处理会员注册表单提交:

    • 在主题的functions.php文件中添加以下代码来处理会员注册的表单提交:
      
      add_action( 'admin_post_nopriv_user_registration', 'handle_user_registration' ); 
      add_action( 'admin_post_user_registration', 'handle_user_registration' );  

    function handle_user_registration() {
    $username = sanitize_user( $_POST['username'] );
    $password = sanitize_text_field( $_POST['password'] );

    $user_id = wp_create_user( $username, $password );

    if ( !is_wp_error( $user_id ) ) {
    wp_redirect( home_url() );
    exit;
    } else {
    wp_redirect( home_url( '/register/' ) );
    exit;
    }
    }

    
    - 保存并更新functions.php文件。 
  3. 创建会员管理页面:

    • 在WordPress后台导航栏中选择“页面” > “添加新页面”;
    • 输入页面标题为“会员管理”;
    • 在页面编辑器中插入会员列表,如下示例代码:
      <?php
       $users = get_users();
       foreach ( $users as $user ) {
          echo '<p>' . esc_html( $user->user_login ) . '</p>';
       }
      ?> 
    • 点击“发布”按钮保存页面。

现在你的WordPress网站已经具备会员注册和会员管理的功能了。用户将能够通过会员注册页面注册,并在会员管理页面中查看会员列表。

注意:上述示例代码仅包含基本的注册和管理功能,你可以根据自己的需求进行扩展和优化。

大家谈论
    我的见解