I have a shortcode that obtains the name of the person logged into wordpress, I would like that shortcode when the person enters a page where I have my shortcode create a .text file and save their name inside it
this is my wordpress shortcode
function alertaLogin( $atts ) {
global $current_user, $user_login;
wp_get_current_user();
add_filter('widget_text', 'apply_shortcodes');
if ($user_login)
return 'hola ' . $current_user->display_name;
else
return 'no ha iniciado session';
}
add_shortcode( 'shortcode_login', 'alertaLogin' );
$contenido = 'saludo';
$archivo = fopen('archivo.txt','a+');
fputs($archivo,$contenido);
fclose($archivo);
How can I create a .txt from this shortcode to store data within it ???
Answers:
Thank you for visiting the Q&A section on Magenaut. Please note that all the answers may not help you solve the issue immediately. So please treat them as advisements. If you found the post helpful (or not), leave a comment & I’ll get back to you as soon as possible.
Method 1
It’s not a good idea to store user’s data on a file that is publicly accessible. A better way would be to create a folder, and store your file under it. Also, it’s better to use WordPress’s filesytem class rather than directly using PHP’s built-in functions. Here’s a quick fix:
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' );
Please notice this is a demonstration and should not be copy-pasted. Accessing filesystem on every page load might slow your website down. You might want to divide this code into 2 different pieces to improve performance.
Also remember to always check if there’s any error while working with the filesystem, e.g. check the result of $wp_filesystem->put_content() and so.
All methods was sourced from stackoverflow.com or stackexchange.com, is licensed under cc by-sa 2.5, cc by-sa 3.0 and cc by-sa 4.0