Question

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 ???

Was it helpful?

Solution

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.

Licensed under: CC-BY-SA with attribution
Not affiliated with wordpress.stackexchange
scroll top