将用户数据存储在可公开访问的文件中不是一个好主意。更好的方法是创建一个文件夹,并将文件存储在该文件夹下。此外,最好使用WordPress的FileSystem类,而不是直接使用PHP的内置函数。这里有一个快速修复方法:
function wpse381320_after_login( $atts ) {
if ( is_user_logged_in() && WP_Filesystem() ) {
global $wp_filesystem;
// Set a path for your folder
$wp_uploads = wp_get_upload_dir();
$content_dir = trailingslashit( $wp_uploads[ \'basedir\' ] ) . \'my-folder\';
$text_file = trailingslashit( $content_dir ) . \'usernames.txt\';
$htaccess_file = trailingslashit( $content_dir ) . \'.htaccess\';
// Get the current user
$current_user = wp_get_current_user();
// Create an empty directory
if ( ! $wp_filesystem->is_dir( $content_dir ) ) {
$wp_filesystem->mkdir( $content_dir, 0755 );
}
// Create the htaccess file
if ( ! $wp_filesystem->is_file( $htaccess_file ) ) {
$htaccess = $wp_filesystem->put_contents( $htaccess_file, \'deny from all\', 0755 );
}
// Create the text file
if ( ! $wp_filesystem->is_file( $text_file ) ) {
$usernames = $wp_filesystem->put_contents( $text_file, \'\', 0755 );
}
// Add username to the file
$usernames = $wp_filesystem->put_contents( $text_file, $current_user->display_name, 0755 );
}
}
add_shortcode( \'shortcode_login\', \'wpse381320_after_login\' );
请注意,这是一个演示,不应复制粘贴。每次加载页面时访问文件系统可能会降低网站速度。您可能希望将此代码分为两部分以提高性能。
还要记住,在使用文件系统时,始终要检查是否有任何错误,例如,检查$wp_filesystem->put_content() 等等。