在Wordpresss中注册我的页面访问量

时间:2021-01-11 作者:Gerardo Marroquin

我有一个短代码,可以获取登录wordpress的人的姓名,我希望当该人进入我的短代码创建的页面时使用该短代码。文本文件并将其名称保存在其中

这是我的wordpress快捷码

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);
如何创建。txt从这个短代码中存储数据???

1 个回复
最合适的回答,由SO网友:Johansson 整理而成

将用户数据存储在可公开访问的文件中不是一个好主意。更好的方法是创建一个文件夹,并将文件存储在该文件夹下。此外,最好使用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() 等等。

相关推荐

如何从USERS-edit.php中删除颜色选择器代码

我知道我不应该改变Wordpress的核心。但如果我想在“用户编辑”中使用仪表板用户配置文件页面。php和删除大块代码(如颜色选择器)的方法。从第259行到第336行-我想全部删除。<?php if ( ! ( IS_PROFILE_PAGE && ! $user_can_edit ) ) : ?> <tr class="user-rich-editing-wrap"> <th scope="