内容营销
WordPress:创建需要用户注册并登录的页面模板
我们正在完成在客户端站点上实现自定义主题的工作,他们要求我们构建某种交互,其中某些页面仅限注册订阅者。 WordPress 确实提供了页面的可见性选项,但这不适合这种情况。
- 私做 – 选择私有可见性仅允许管理员和编辑者查看内容。
- 密码保护 – 需要为每个页面应用唯一的代码才能查看内容。
起初,我们考虑过实现第三方插件,但解决方案很简单。 我们可以创建一个独特的模板,要求查看者注册并登录才能查看该页面。
WordPress 模板:仅限订阅者
首先,我们复制了客户的页面模板(page.php
) 子主题。 要创建模板,您需要在页面顶部添加一些代码:
<?php /* Template Name: Subscribers Only */ ?>
接下来,在页面代码中查找显示内容的行。 它看起来应该像这样:
<?php the_content(); ?>
现在,您需要在该行中包装一些代码:
<?php
$redirect_url = get_permalink(); // Get the current page's URL
if (is_user_logged_in()) :
?>
<h2><?php the_title(); ?></h2>
<?php the_content(); ?>
<?php else : ?>
<h2>Subscriber Only</h2>
<p>We're sorry, the content you are trying to reach is restricted to certain roles. <a href="<?php echo wp_login_url($redirect_url); ?>">Log in</a> to access it.</p>
<?php endif; ?>
以下是对代码要点的解释:
$redirect_url = get_permalink();
:此行检索当前页面的 URL 并将其存储在变量中$redirect_url
.if (is_user_logged_in()) :
:此条件语句检查用户是否已经登录。- 如果用户登录,则执行该块中的代码。
<h2><?php the_title(); ?></h2>
:显示当前页面的标题。<?php the_content(); ?>
:显示当前页面的内容。
- 如果用户未登录,则代码中
else
块被执行。<h2>Subscriber Only</h2>
:这将显示一个标题,表明内容受到限制。<p>We're sorry, the content you are trying to reach is restricted to certain roles. <a href="<?php echo wp_login_url($redirect_url); ?>">Log in</a> to access it.</p>
:这会显示一条消息,解释内容仅限于某些角色,并提供“登录”链接。 链接的href
属性设置为生成的登录 URLwp_login_url($redirect_url)
,确保用户登录后重定向回当前页面。
此代码有效地检查用户是否已登录,如果没有,则鼓励他们登录以访问受限内容,并通过链接将他们引导回他们尝试查看的页面。
按特定用户角色查看
如果您愿意,您还可以将内容限制为特定用户角色:
<?php
$allowed_roles = array('subscriber', 'editor', 'author'); // Add the roles you want to allow
$user = wp_get_current_user();
$redirect_url = get_permalink();
if (array_intersect($allowed_roles, $user->roles)) :
?>
<h2><?php the_title(); ?></h2>
<?php the_content(); ?>
<?php else : ?>
<h2>Restricted Access</h2>
<p>We're sorry, the content you are trying to reach is restricted to certain roles.
<a href="<?php echo wp_login_url($redirect_url); ?>">Log in</a> to access it.</p>
<?php endif; ?>
以下是对代码要点的解释:
$allowed_roles = array('subscriber', 'editor', 'author');
:此行创建允许的角色数组,指定允许哪些用户角色访问内容。 您可以自定义此数组以包含您想要允许的角色。$user = wp_get_current_user();
:此代码检索有关当前用户的信息,包括他们的角色。$redirect_url = get_permalink();
:该行将当前页面的 URL 存储在$redirect_url
变量,该变量将用于在用户登录后将用户重定向回当前页面。if (array_intersect($allowed_roles, $user->roles)) :
:此条件语句检查用户的角色是否与列表中列出的角色相交。$allowed_roles
大批。 换句话说,它检查用户是否具有允许的角色之一。- 如果用户具有允许的角色之一,则执行此块中的代码。
<h2><?php the_title(); ?></h2>
:显示当前页面的标题。<?php the_content(); ?>
:显示当前页面的内容。
- 如果用户不具有允许的角色之一,则
else
块被执行。<h2>Restricted Access</h2>
:这将显示一个标题,表明内容受到限制。<p>We're sorry, the content you are trying to reach is restricted to certain roles. <a href="<?php echo wp_login_url($redirect_url); ?>">Log in</a> to access it.</p>
:这会显示一条消息,解释内容仅限于某些角色,并提供“登录”链接。 链接的href
属性设置为生成的登录 URLwp_login_url($redirect_url)
,确保用户登录后重定向回当前页面。
此代码有效地限制对特定角色的访问,如果用户不具有允许的角色之一,它会提示他们使用一个链接登录,该链接将在登录后将他们重定向回当前页面。
选择您的模板
要使用该页面,您需要选择 仅限订阅者 页面选项高级部分(侧边栏)中的页面模板。 这会将页面限制为登录的读者或您定义的角色。