questions

Show add_filter only if user is admin

Rate this post

i have this code and want only to happens when user is connected as admin. (Shows a limit count)

 

/**
 * Display how many spots are left in the choice label when using the GP Limit Choices perk
 * http://gravitywiz.com/gravity-perks/
 */

add_filter( 'gplc_remove_choices', '__return_false' );

add_filter( 'gplc_pre_render_choice', 'my_add_how_many_left_message', 10, 5 );



function my_add_how_many_left_message( $choice, $exceeded_limit, $field, $form, $count ) {

    $limit         = rgar( $choice, 'limit' );
    $how_many_left = max( $limit - $count, 0 );

    $message = "($how_many_left spots left)";

    $choice['text'] = $choice['text'] . " $message";

    return $choice;
}

Thanks!!!

 

✔️Solution:

Checking administrator capability for the current user probably could help to solve the problem

add_filter( 'gplc_remove_choices', function ( $result ) {
    return current_user_can( 'administrator' ) ? false : $result;
} );

add_filter( 'gplc_pre_render_choice', 'my_add_how_many_left_message', 10, 5 );


function my_add_how_many_left_message( $choice, $exceeded_limit, $field, $form, $count ) {
    if ( ! current_user_can( 'administrator' ) ) {
        return $choice;
    }

    $limit         = rgar( $choice, 'limit' );
    $how_many_left = max( $limit - $count, 0 );

    $message = "($how_many_left spots left)";

    $choice['text'] = $choice['text'] . " $message";

    return $choice;
}

According to WordPress: every user has its role, every role has its capabilities. And checking capability instead of role could be useful for the problem.

Leave a Reply

Your email address will not be published.

Back to top button