我们可以在这里为每个帖子创建一个元框,并为其分配一个用户。然后,在我们的帖子页面上,检查当前用户是否与帖子相关。
如果他们与此无关,则将他们重定向回主页或其他地方。
我将使用元框的下拉列表,并用用户填充它。
// Hook into the add_meta_boxes action
add_action( \'add_meta_boxes\', \'kreigd_user_metabox\' );
function kreigd_user_metabox() {
// Create a new metabox
add_meta_box(
\'kreigd-user-list\', // ID
\'User List\', // Title
\'kreigd_user_list_callback\', // Callback
array(\'post\',\'page\'), // Post types
\'normal\',
\'high\'
);
}
// Output the content for metabox
function kreigd_user_list_callback() {
// $post is already set, and contains an object: the WordPress post
global $post;
$values = get_post_custom( get_the_ID() );
// Get the current assigned user
$user_id = isset( $values[\'user_id\'][0] ) ? $values[\'user_id\'][0] : 0;
// We\'ll use this nonce field later on when saving.
wp_nonce_field( \'kreigd_nonce\', \'kreigd_user_list_nonce\' );?>
<p>
<label for="kreigd_select"><?php _e(\'Choose a user\',\'text-domain\'); ?></label>
<select name="kreigd_select" id="kreigd_select"><?php
$users = get_users(); // Retrieve a list of users
// Run a loop and add every user to the list
foreach ( $users as $user ){ ?>
<option
value="<?php echo esc_html( $user->ID ); ?>"
<?php selected( $user->ID, $user_id ); ?>
>
<?php echo esc_html( $user->display_name ); ?>
</option><?php
} ?>
</select>
</p><?php
}
// Save the user to meta box on post save
add_action( \'save_post\', \'mymovieflaws_meta_box_save\' );
function mymovieflaws_meta_box_save( $post_id ){
// Don\'t save it on autosave
if( defined( \'DOING_AUTOSAVE\' ) && DOING_AUTOSAVE )
return;
// If the nonce is not correct, or the value is not set, return
if( !isset( $_POST[\'kreigd_select\'] ) || !wp_verify_nonce( $_POST[\'kreigd_user_list_nonce\'], \'kreigd_nonce\' ) )
return;
// If current user doesn\'t have the privilege to save a post, return
if( !current_user_can( \'edit_post\', $post_id ) )
return;
$allowed = array( \'a\' => array( \'href\' => array() ) );
// Save the user\'s ID
update_post_meta( $post_id, \'user_id\', wp_kses( $_POST[\'kreigd_select\'], $allowed ) );
}
您可以通过使用引导选择来利用这一点,并将搜索选项添加到选择器中。这样,您就可以快速找到每个用户,而无需查看整个列表。