根据用户角色限制点击按钮

Posted

技术标签:

【中文标题】根据用户角色限制点击按钮【英文标题】:Limit clicks on button based on user role 【发布时间】:2021-12-12 01:26:49 【问题描述】:

我有一个受限页面,其中包含 WordPress 中仅限成员的条目,在此页面上,每个条目都有一个“查看更多”按钮。我正在寻找一种解决方案,根据用户分配的用户角色来限制对该特定按钮的点击。该按钮有自己的类“.se-mere-knap”。

例如,用户角色 1 从创建订阅时起需要点击此按钮 5 次。如果他们达到点击次数限制,他们将无法再通过点击按钮访问任何条目。订阅运行一个月,并且有不同的唯一用户,因此需要在订阅开始后 30 天后为该特定用户重置。

我已经根据用户角色编写了代码,用于将脚本排入队列以在子主题 functions.php 中加载 .js 文件:

     function add_custom_script_1() 
    
    if ( current_user_can( 'um_5-klik-test' ) ) 
        
    wp_register_script('custom_script_1', home_url() . '/button-restrict/button-restrict-5.js', array( 'jquery' ));
    wp_enqueue_script('custom_script_1');  



add_action( 'wp_enqueue_scripts', 'add_custom_script_1', 999);

其次,在@Digi Coder 的帮助下,button-restrict-5.js 如下:

"use strict";

    viewmore_settings();

    // checks if the expiry date has elapsed
    function check_viewmore_expiry() 
        // set the current date
        var curDate = new Date().getTime();
        // get the difference between the expiry date and current date
        var distance = localStorage.expDate - curDate;
        // round up to get the exact date remaining
        var days = Math.floor( distance / ( 1000 * 60 * 60 * 24 ) );
        // log remaining date to the console
        console.log( days + ' days left.' );
        // check if the expiry date has elapsed
        if ( distance < 0 ) 
            // log expiry message to the console
            console.log( 'Time Expired.' );
            // reset the expiry date to 30 days
            localStorage.expDate = new Date().setUTCSeconds( 60 * 60 * 24 * 30 );
            // reset the counter to zero
            localStorage.counter = 0;
        
    

    // disables view more button if counter limit is reached
    function viewmore_button_disabled() 
        // the html button that user clicks
        var btn = document.querySelector( 'button.se-mere-knap' );
        // check if user click action is up to five or greater than five
        if ( Number( localStorage.counter ) >= 5 ) 
            // disable the button
            btn.disabled = true;
            // button is disabled
            return true;
        
        // button is not disabled
        return false;
    

    // Sets value for the counter and expiry date stored in local storage
    function viewmore_settings() 
        // check for local storage support
        if ( typeof Storage !== 'undefined' ) 
            // check if counter is not set in storage
            if ( localStorage.counter === undefined ) 
                // set counter to zero
                localStorage.counter = 0;
            
            // check if expDate is not set in storage
            if ( localStorage.expDate === undefined ) 
                // set expiry date to 30 days
                localStorage.expDate = new Date().setUTCSeconds( 60 * 60 * 24 * 30 );
            
            // check if the expiry date has elapsed
            check_viewmore_expiry();
            // disable view more button if counter limit is reached
            viewmore_button_disabled();
         else 
            // display message for browsers that does not support storage
            window.alert( 'Din browser understøtter desværre ikke vores funktioner.' );
        
    

    // runs when user clicks the view more button
    function viewmore_func() 
        // check for local storage support
        if ( typeof Storage !== 'undefined' ) 
            // check if the expiry date has elapsed
            check_viewmore_expiry();
            // check if the view more button is disabled
            if ( viewmore_button_disabled() ) 
                // display alert message for maximum click attempt
                window.alert( 'Din grænse for antal klik ind på en jobsøgendes profil er nået. Du kan opgradere til flere klik, gennem din virksomhedsprofil. Antal af klik bliver nulstillet hver 30. dag.' );
             else 
                // increment counter for every user click action
                localStorage.counter = Number( localStorage.counter ) + 1;
                // log the counter value to console
                console.log( localStorage.counter );
                // redirect user to resource page or show user the content
                window.location.assign( 'index.php' );
            
        
    

document.querySelector( 'button.se-mere-knap' ).addEventListener( 'click', viewmore_func ); 

我创建了一个具有此角色的用户进行测试,但它不起作用。当我超过 5 次点击的限制时,什么也没有发生。没有设置点击次数限制。

【问题讨论】:

【参考方案1】:

PHP

function add_custom_script_1() 
    // check if current user has capability of "um_5-klik-test"
    if ( current_user_can( 'um_5-klik-test' ) ) 
        // register custom_script_1
        wp_register_script('custom_script_1', home_url() . '/button-restrict/button-restrict-5.js', array( 'jquery' ));
        // enqueue custom_script_1
        wp_enqueue_script('custom_script_1');
        // localize custom_script_1
        wp_localize_script( 'custom_script_1', 'user',
            array(
                // set ID key to current user id
                'ID' => get_current_user_id(),
            )
        );
    

add_action( 'wp_enqueue_scripts', 'add_custom_script_1', 999);

HTML

<button class="se-mere-knap">View More</button>

javascript - (button-restrict-5.js)

    "use strict";

    viewmore_settings();

    // checks if the expiry date has elapsed
    function check_viewmore_expiry() 
        // get stored data from local storage and convert from JSON string to original format
        var viewmore_data = JSON.parse( localStorage.viewmore );
        // loop through the stored data
        viewmore_data.forEach( ( item, index ) => 
            // check if the stored user match the current user
            if ( item.userID == user.ID ) 
                // set the current date
                var curDate = new Date().getTime();
                // get the difference between the expiry date and current date
                var distance = item.expDate - curDate;
                // round up to get the exact date remaining
                var days = Math.floor( distance / ( 1000 * 60 * 60 * 24 ) );
                // log remaining date to the console
                console.log( days + ' days left.' );
                // check if the expiry date has elapsed
                if ( distance < 0 ) 
                    // log expiry message to the console
                    console.log( 'Time Expired.' );
                    // reset the expiry date to 30 days
                    item.expDate = new Date().setUTCSeconds( 60 * 60 * 24 * 30 );
                    // reset the counter to zero
                    item.counter = 0;
                    // store data as JSON string in local storage
                    localStorage.viewmore = JSON.stringify( viewmore_data );
                
            
         );
    

    // disables view more button if counter limit is reached
    function viemore_button_disabled() 
        // set status to false: button is not disabled
        var status = false;
        // get data from local storage and convert from JSON string to original format
        var viewmore_data = JSON.parse( localStorage.viewmore );
        // loop through the stored data
        viewmore_data.forEach( ( item, index ) => 
            // check if the stored user match the current user and also check if click action is up to five or greater than five
            if ( item.userID == user.ID && Number( item.counter ) >= 5 ) 
                // select all button with the class of view-more, typecast them to array and loop through them.
                [...document.querySelectorAll( 'button.se-mere-knap' )].forEach( ( btn, index ) => 
                    // hide the button
                    btn.style.display = 'none';
                 );
                // set status to true: button is disabled
                status = true;
            
         );
        // return the value of status
        return status;
    

    // Sets value for the counter and expiry date stored in local storage
    function viewmore_settings() 
        // check for local storage support
        if ( typeof Storage !== 'undefined' ) 
            // set expiry date to 30 days
            var expDate = new Date().setUTCSeconds( 60 * 60 * 24 * 30 );
            // set counter to zero
            var counter = 0;
            // set user id
            var userID = user.ID;
            // create object containing expiry date, counter and user id
            var data =  expDate, counter, userID ;
            // check if no data is stored in local storage
            if ( localStorage.viewmore === undefined ) 
                // put data object inside an array
                var viewmore_data = [ data ];
                // store data as JSON string in local storage
                localStorage.viewmore = JSON.stringify( viewmore_data );
             else 
                // get data from local storage and convert from JSON string to original format
                var viewmore_data = JSON.parse( localStorage.viewmore );
                // get all stored user ids from data
                var users_id_arr = viewmore_data.map( ( item, index ) => 
                    return item.userID
                 );
                // check stored user ids does not match the current id
                if ( users_id_arr.indexOf( userID ) === -1 ) 
                    // append new object containing expiry date, counter and user id to data
                    viewmore_data.push( data );
                    // store data as JSON string in local storage
                    localStorage.viewmore = JSON.stringify( viewmore_data );
                
            
            // check if the expiry date has elapsed
            check_viewmore_expiry();
            // disable view more button if counter limit is reached
            viemore_button_disabled();
         else 
            // display message for browsers that does not support storage
            window.alert( 'Your web browser does not support local storage' );
        
    

    // runs when user clicks the view more button
    function viewmore_func() 
        // check for local storage support
        if ( typeof Storage !== 'undefined' ) 
            // check if the expiry date has elapsed
            check_viewmore_expiry();
            // check if the view more button is disabled
            if ( viemore_button_disabled() ) 
                // display alert message for maximum click attempt
                window.alert( 'You have reached the limit!' );
             else 
                // get data from local storage and convert from JSON string to original format
                var viewmore_data = JSON.parse( localStorage.viewmore );
                // loop through stored data
                viewmore_data.forEach( ( item, index ) => 
                    // check if the stored user match the current user
                    if ( item.userID == user.ID ) 
                        // increment counter
                        viewmore_data[index].counter = Number( item.counter ) + 1;
                    
                 );
                // store viewmore data array as JSON string in local storage
                localStorage.viewmore = JSON.stringify( viewmore_data );
                // redirect user to resource page or show user the content
                // window.location.assign( 'index.php' );
            
        
    

    // select all button with the class of se-mere-knap, typecast them to array and loop through them.
    [...document.querySelectorAll( 'button.se-mere-knap' )].forEach( ( btn, index ) => 
        // add event that will run when the button is clicked
        btn.addEventListener( 'click', viewmore_func );
     );

【讨论】:

非常感谢!该按钮没有#,而是一个类。如何确保代码仅适用于具有此类 (.view-more) 的特定按钮?我是这个领域的新手 - 我如何设置 var countervar expDate 让我们说一个本地存储? 对于类名,假设按钮类名是.view-more,设置var btn如下:var btn = document.querySelector( 'button.view-more' );. 好的,谢谢!如何从本地存储或 cookie 设置和调用它?为了让它是动态的。 @markpnielsen 我已经编辑了我的答案。您现在可以从本地存储调用。享受:-) 感谢@Digi Coder!我用onclick="viewmore_func();" 看到你的HTML。我的按钮是用另一个插件生成的,我似乎无法编辑按钮 HTML。我只能为它设置自定义 CSS 类。如何解决这个问题?

以上是关于根据用户角色限制点击按钮的主要内容,如果未能解决你的问题,请参考以下文章

雪花中角色和用户的限制

根据用户角色限制用户控制的功能

如何根据登录状态/角色限制/控制用户可以访问的导航路线?

根据角色限制对登录symfony的访问

如何使用spring security根据角色限制对html页面的访问?

限制按钮点击次数