我试图在WP上创建一个会员网站,每个会员都只能访问为他们创建的特定页面。我的意思是,只允许一个成员查看页面上的内容,而该页面仅限于其他人。我只是想授权一个成员访问一个页面。我不知道在任何插件的帮助下这是否可行
仅允许特定成员访问页面
4 个回复
SO网友:brasofilo
与Dominic的概念相同(不需要成员插件),但扩展为使用一个元框,只对管理员可见,并带有一个包含所有用户的下拉列表(例外)。
借用和改编的代码from this answer. 加入functions.php
:
// List Users
add_action( \'admin_init\', \'wpse_33725_users_meta_init\' );
// Save Meta Details
add_action( \'save_post\', \'wpse_33725_save_userlist\' );
function wpse_33725_users_meta_init()
{
if( current_user_can( \'administrator\' ) )
add_meta_box( \'users-meta\', \'Authorized User\', \'wpse_33725_users_meta_box\', \'page\', \'side\', \'high\' );
}
function wpse_33725_users_meta_box()
{
global $post;
$custom = get_post_custom( $post->ID );
$users = $custom["users"][0];
// prepare arguments
$user_args = array(
// exclude users from the list using an array of ID\'s
\'exclude\' => array(1),
// order results by display_name
\'orderby\' => \'display_name\'
);
// Create the WP_User_Query object
$wp_user_query = new WP_User_Query($user_args);
// Get the results
$authors = $wp_user_query->get_results();
// Check for results
if ( !empty($authors) )
{
// Name is your custom field key
echo "<select name=\'users\'>";
echo \'<option value=0>All</option>\';
// loop trough each author
foreach ( $authors as $author )
{
$author_id = get_post_meta( $post->ID, \'users\', true );
$author_selected = ( $author_id == $author->ID ) ? \'selected="selected"\' : \'\';
echo \'<option value=\'.$author->ID.\' \'.$author_selected.\'>\'.$author->user_nicename.\'</option>\';
}
echo "</select>";
}
else
{
echo \'No authors found\';
}
}
function wpse_33725_save_userlist()
{
global $post;
if ( defined( \'DOING_AUTOSAVE\' ) && DOING_AUTOSAVE )
{
return $post->ID;
}
update_post_meta( $post->ID, "users", $_POST["users"] );
}
要检查权限,这在“循环输入”之外起作用page.php
:$the_user = get_post_meta( $wp_query->post->ID, \'users\', true );
if( \'0\' == $the_user || empty( $the_user ) )
{
echo "this is a public page";
}
else
{
if( get_current_user_id() == $the_user )
echo "this page is for you";
else
{ // NOTHING TO SEE, GO TO FRONT PAGE
wp_redirect(\'/\');
header("Status: 302");
exit;
}
}
SO网友:Zach Russell
我还建议您查看付费会员资格pro(免费)、Premise登录页(付费)和restrict content pro(付费)等插件。这些都可以解决你的问题。
SO网友:Dominic
您可以将允许用户的ID添加到特定页面上的自定义字段中。然后使用get_current_user_id()
并在显示内容之前查看是否匹配。
SO网友:Asha
您可以检查current user id 在页的开头get_current_user_id() 功能或您可以检查更多-https://developer.wordpress.org/reference/functions/get_current_user_id/ 并相应地应用条件。
结束