与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;
}
}