如何使用WordPress开发会员网站:第3部分

最终产品图片
您将要创造的

在本系列的前面,我们介绍了如何自定义WordPress登录和注册表单。 然后,我们在注册表格中添加了一些自定义字段。 今天,在本系列的第三篇也是最后一部分中,我们将介绍如何为您的站点用户开发“我的帐户”部分,以便用户可以编辑其个人资料信息。

页面设置

我们要做的第一件事是创建一个页面模板来容纳我们的内容。 我想在页面模板的前面加上“模板”一词。 所以我的文件名为template-user-profile.php,打开的PHP如下所示:

<?php

/**
 * Template Name: User Profile
 */

我已经将其保存在主题目录的根目录中。 如果您不熟悉WordPress页面模板 ,建议您阅读上面的链接。 他们非常方便。

现在,让我们转到WordPress后端,创建一个名为“配置文件”的页面,然后在“ 页面属性”元框中为其分配新创建的页面模板。 发布此页面后,前端应该有一个空白页面: http:// yourdomain / profile

用户资料

现在将一些内容注入我们的页面。 我们希望结构是页面内容(即WordPress所见即所得中写的任何内容),然后是我们的个人资料表单。

从page.php获取代码并将其用作页面模板的起点通常会很有帮助。 这段代码根据您的主题而有所不同,但是很可能包含一个循环,它会吐出一些页面内容。 通常使用WordPress函数get_template_part()获取内容部分。 在检索内容的下面,让我们插入表单HTML。 因此,回顾一下:

  1. 将代码从page.php复制并粘贴到我们的页面模板中。
  2. 查找内容的输出位置。
  3. 在此之下,插入以下代码,然后我们将逐步进行介绍:
<form role="form" action="" id="user_profile" method="POST">
    <?php wp_nonce_field( 'user_profile_nonce', 'user_profile_nonce_field' ); ?>
    <div class="form-group">
        <label for="first_name"><?php _e( 'First name', 'sage' ); ?></label>
        <input type="text" class="form-control" id="first_name" name="first_name" placeholder="<?php _e( 'First name', 'sage' ); ?>" value="<?php echo $user_info->first_name; ?>">
    </div>
    <div class="form-group">
        <label for="last_name"><?php _e( 'Last name', 'sage' ); ?></label>
        <input type="text" class="form-control" id="last_name" name="last_name" placeholder="<?php _e( 'Last name', 'sage' ); ?>" value="<?php echo $user_info->last_name; ?>">
    </div>
    <div class="form-group">
        <label for="twitter_name"><?php _e( 'Twitter name', 'sage' ); ?></label>
        <input type="text" class="form-control" id="twitter_name" name="twitter_name" placeholder="<?php _e( 'Twitter name', 'sage' ); ?>" value="<?php echo $user_info->twitter_name; ?>">
    </div>
    <div class="form-group">
        <label for="email"><?php _e( 'Email address', 'sage' ); ?></label>
        <input type="email" class="form-control" id="email" name="email" placeholder="<?php _e( 'Email address', 'sage' ); ?>" value="<?php echo $user_info->user_email; ?>">
    </div>
    <div class="form-group">
        <label for="pass1"><?php _e( 'Password', 'sage' ); ?></label>
        <input type="password" class="form-control" id="pass1" name="pass1" placeholder="<?php _e( 'Password', 'sage' ); ?>">
    </div>
    <div class="form-group">
        <label for="pass2"><?php _e( 'Repeat password', 'sage' ); ?></label>
        <input type="password" class="form-control" id="pass2" name="pass2" placeholder="<?php _e( 'Repeat password', 'sage' ); ?>">
    </div>
    <button type="submit" class="btn btn-default"><?php _e( 'Submit', 'sage' ); ?></button>
</form>

这里没有什么疯狂的事情:表单使用的是Bootstrap标记,因为我们的主题是建立在Bootstrap上的。 其他需要注意的是,该表单是使用POST方法发送的,并且其中包含了wp_nonce_field,这是一种安全令牌,可帮助防止恶意攻击。 如果您不熟悉WordPress的Nonnce,建议您阅读本文

检索数据

将其放置在适当的位置后,您应该在网站的前面有一个表单,但是并没有做太多事情。 我们希望它显示已登录用户的数据。 您可能已经注意到我们表单中的value属性正在回显一些PHP。

value="<?php echo $user_info->first_name; ?>"

由于我们尚未编写代码,因此该$user_info对象目前不存在,所以让我们从此处开始。 将以下代码粘贴到template-user-profile.php中的表单之前。

<?php

/**
 * Gets the user info.
 * Returned in an object.
 * 
 * http://codex.wordpress.org/Function_Reference/get_userdata
 */

$user_id = get_current_user_id();
$user_info = get_userdata( $user_id );

使用某些WordPress本机功能,它可以获取当前用户的ID,并由此我们可以获取用户的数据。 这存储在名为$user_info的对象中,并且如上所示,我们可以很容易地检索用户数据。 要查看存储在该对象中的所有数据,可以像这样运行var_dump<?php var_dump($user_info); ?> <?php var_dump($user_info); ?> 。 这对于调试或仅查看您可以访问的内容很有用。

处理数据

难题的最后一部分是处理数据,从而允许用户编辑其个人资料。 为了使事情井井有条,我已将会员代码放入一个文件名为“ membership.php”的文件中。 该文件位于lib目录中,并已包含在我们的functions.php文件中。 完成此操作后,在代码编辑器中打开新创建的Membership.php文件,然后创建用于处理用户数据的函数。

首先,让我们快速了解一下逻辑。 当单击提交按钮时,我们要检查是否已发送我们的现时字段-这将检查数据是否来自正确的位置。

如果满足该条件,我们希望获取当前用户的ID,因为我们将需要该ID来存储数据。 然后,我们想将数据排列成WordPress喜欢的结构-在这种情况下,它是具有特定键的数组。 在保存数据之前,我们还希望对其进行验证和消毒。 最后,我们希望向用户显示成功或错误的消息。

和所有看起来像这样的代码:

<?php

/**
 * Process the profile editor form
 */
function tutsplus_process_user_profile_data() {
    
    if ( isset( $_POST['user_profile_nonce_field'] ) && wp_verify_nonce( $_POST['user_profile_nonce_field'], 'user_profile_nonce' ) ) {
        
        // Get the current user id.
        $user_id = get_current_user_id();
        
        // Put our data into a better looking array and sanitize it.
        $user_data = array(
            'first_name' => sanitize_text_field( $_POST['first_name'] ),
            'last_name' => sanitize_text_field( $_POST['last_name'] ),
            'user_email' => sanitize_email( $_POST['email'] ),
            'twitter_name' => sanitize_text_field( $_POST['twitter_name'] ),
            'user_pass' => $_POST['pass1'],
        );
        
        if ( ! empty( $user_data['user_pass'] ) ) {
            
            // Validate the passwords to check they are the same.
            if ( strcmp( $user_data['user_pass'], $_POST['pass2'] ) !== 0 ) {

                wp_redirect( '?password-error=true' );

                exit;
            }

        } else {

            // If the password fields are not set don't save.
            unset( $user_data['user_pass'] );
        }

        // Save the values to the post.
        foreach ( $user_data as $key => $value ) {

            $results = '';
            
            // http://codex.wordpress.org/Function_Reference/wp_update_user
            if ( $key == 'twitter_name' ) {

                $results = update_user_meta( $user_id, $key, $value );
                unset( $user_data['twitter_name'] );

            } elseif ( $key == 'user_pass' ) {

                wp_set_password( $user_data['user_pass'], $user_id );
                unset( $user_data['user_pass'] );

            } else {

                // Save the remaining values.
                $results = wp_update_user( array( 'ID' => $user_id, $key => $value ) );

            }

            if ( ! is_wp_error( $results ) ) {
                
                wp_redirect( '?profile-updated=true' );
                
            }
        }

        wp_redirect( '?profile-updated=false' );
        
        exit;
    }
}

add_action( 'tutsplus_process_user_profile', 'tutsplus_process_user_profile_data' );

现在,您可能会注意到,正在使用三种不同的WordPress函数保存数据:

  • update_user_meta()为Twitter名称
  • wp_set_password()作为密码
  • wp_update_user()用于剩余数据

您对此提出质疑是正确的。 基本上,需要使用相对功能而不是常规更新用户功能来处理自定义元数据(Twitter名称)。 至于密码,虽然它可以与wp_update_user() ,但是我遇到了问题,因此倾向于使用此方法。 请记住,这只是一个指南,并且代码通常旨在演示实现您的需求的不同方法。

好的,现在我们有了处理数据的功能,但是没有在任何地方调用它。 在我们的功能结束时,您可以看到有一个与其相关的动作。 因此,要调用该函数,我们只需要使用提供的WordPress: do_action(); 。 因此,将此行粘贴到我们前面创建的“用户个人资料”页面模板中的表单上方:

<?php do_action( 'tutsplus_process_user_profile' ); ?>

有了适当的设置,当我们提交表单时,它应该运行我们的函数并处理数据。

错误和成功消息

错误和成功消息

我们的个人资料表格应立即保存或拒绝数据。 可能这两个密码不相同,并且没有保存。 没有消息可提供用户反馈。 让我们为用户节省一些痛苦,并给他们一些消息。

在我们的tutsplus_process_user_profile()函数中,您可能已经注意到,根据处理结果,它会将不同的查询字符串附加到URL。 因此,如果一切都保存成功,则我们的URL将附加?profile-updated=true ,并且它们会根据结果而有所不同。 我们需要做的是基于这些响应触发一条消息。

在下面,我使用了一个过滤器来获取内容,通过$_GET的魔力,我们可以检查参数并吐出我们需要的内容。

<?php

/**
 * Display the correct message based on the query string.
 *
 * @param string $content Post content.
 *
 * @return string Message and content.
 */
function tutsplus_display_messages( $content ) {

    if ( 'true' == $_GET['profile-updated'] ) {

        $message = __( 'Your information was successfully updated', 'sage' );
        $message_markup = tutsplus_get_message_markup( $message, 'success' );

    } elseif ( 'false' == $_GET['profile-updated'] ) {

        $message = __( 'There was an error processing your request', 'sage' );
        $message_markup = tutsplus_get_message_markup( $message, 'danger' );

    } elseif ( 'true' == $_GET['password-error'] ) {

        $message = __( 'The passwords you provided did not match', 'sage' );
        $message_markup = tutsplus_get_message_markup( $message, 'danger' );

    }

    return $message_markup . $content;
}

add_filter( 'the_content', 'tutsplus_display_messages', 1 );

好的, tutsplus_get_message_markup() ,我们在上面使用了一个叫做tutsplus_get_message_markup()的函数,但是我们还没有定义它。 它带有两个参数:

  • 字符串:要显示的消息
  • 字符串:根据Bootstrap显示的警报严重性

因此,让我们定义我们的tutsplus_get_message_markup()函数:

<?php

/**
 * A little helper function to generate the Bootstrap alerts markup.
 *
 * @param string $message Message to display.
 * @param string $severity Severity of message to display.
 * 
 * @return string Message markup.
 */
function tutsplus_get_message_markup( $message, $severity ) {

    $output = '<div class="alert alert-' . $severity . ' alert-dismissable">';
        $output .= '<button type="button" class="close" data-dismiss="alert" aria-hidden="true">';
            $output .= '<i class="fa fa-times-circle"></i>';
        $output .= '</button>';
        $output .= '<p class="text-center">' . $message . '</p>';
    $output .= '</div>';

    return $output;
    
}

大。 现在我们的成员可以查看是否保存了他们的数据。

额外信用

因此,现在我们有一个可供会员网站使用的原型。 WordPress附带了许多此功能,但是我们对其样式进行了调整,以使其对用户有更好的体验。 因此,现在让我们加点“ I”,然后再加上“ T”,以改善体验。

首先,我们要阻止未登录的用户访问个人资料页面 。 一个简单的重定向到主页即可。 我已经做了一个可以做到这一点的功能,并且在我想由登录用户唯一访问的页面上调用它。

这是放置在membership.php中的函数:

<?php

/**
 * Makes pages where this function is called only
 * accessible if you are logged in.
 */
function tutsplus_private_page() {

    if ( ! is_user_logged_in() ) {
        
        wp_redirect( home_url() );
        
        exit();
        
    }
    
}

现在,我们可以简单地在“用户个人资料”页面模板顶部调用该函数。

接下来,我们希望将用户(当然,订户)保留在管理区域之外 。 最重要的是,让我们删除登录用户的管理栏 。 再次将其放在我们的membership.php中。

<?php

/**
 * Stop subscribers from accessing the backed
 * Also turn off the admin bar for anyone but administrators.
 */
function tutsplus_lock_it_down() {
    
    if ( ! current_user_can('administrator') && ! is_admin() ) {
        
        show_admin_bar( false );
        
    }
    
    if ( current_user_can( 'subscriber' ) && is_admin() ) {
        
        wp_safe_redirect( 'profile' );
        
    }
    
}

add_action( 'after_setup_theme', 'tutsplus_lock_it_down' );

最后,导航登录/注销屏幕并非易事。 让我们添加一些特定于用户的导航 。 我所做的是创建一个输出相关代码的函数,然后在呈现主导航的templates / header.php中调用此函数。

<?php

/**
 * Outputs some user specific navigation.
 */
function tutsplus_user_nav() {

    $user_id = get_current_user_id();
    $user_name = get_user_meta( $user_id, 'first_name', true );
    $welcome_message = __( 'Welcome', 'sage' ) . ' ' . $user_name;

    echo '<ul class="nav navbar-nav navbar-right">';

        if ( is_user_logged_in() ) {

            echo '<li>';
                echo '<a href="' . home_url( 'profile' ) . '">' . $welcome_message . '</a>';
            echo '</li>';
            echo '<li>';
                echo '<a href="' . wp_logout_url( home_url() ) . '">' . __( 'Log out', 'sage' ) . '</a>';
            echo '</li>';

        } else {

            echo '<li>';
                echo '<a href="' . wp_login_url() . '">' . __( 'Log in', 'sage' ) . '</a>';
            echo '</li>';

        }

    echo '</ul>';
    
}

摘要

WordPress是会员应用程序的绝佳基础。 它已经具有与此类应用程序相关的大量功能。 最重要的是,WordPress的人们已经很容易挂接到事件并过滤内容,因此我们可以扩展已经存在的内容。

我希望这为您提供了开发自己的会员站点的方法,思想和知识。 这绝不是有关此主题的完整指南,而是作为基础。

欢迎任何反馈,我将尽力回答评论中的任何问题。

注意事项

请注意:如果您要从GitHub存储库下载代码,那么它将包含所有文件来启动和运行您的主题。 这个想法是,您可以获取存储库,然后运行必要的Gulp和Bower命令 ,您就可以离开! 如果只需要包含特定于该系列的代码的文件,则下面列出这些文件:

翻译自: https://code.tutsplus.com/tutorials/how-to-develop-a-membership-site-with-wordpress-part-3--cms-23391

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值